Hand of Straights
Medium
GreedyHash MapSorting
Problem
Given a hand of cards and groupSize, return true iff the cards can be partitioned into groups of consecutive ascending cards of length groupSize.
Example 1
Input: hand=[1,2,3,6,2,3,4,7,8], groupSize=3
Output: true
Constraints
- 1 ≤ hand.length ≤ 10⁴
Approach — Hashing & Counting
This is a Hashing & Counting problem. The idea: store what you've seen in a hash map for O(1) lookups, trading a little space to avoid a nested scan. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(n) space.
Solution code
Python
class Solution:
def isNStraightHand(self, hand, groupSize):
from collections import Counter
if len(hand) % groupSize:
return False
count = Counter(hand)
for x in sorted(count):
c = count[x]
if c > 0:
for k in range(x, x + groupSize):
if count[k] < c:
return False
count[k] -= c
return True
Java
import java.util.*;
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) return false;
TreeMap<Integer,Integer> count = new TreeMap<>();
for (int c : hand) count.merge(c, 1, Integer::sum);
while (!count.isEmpty()) {
int start = count.firstKey();
for (int i = 0; i < groupSize; i++) {
int k = start + i;
Integer v = count.get(k);
if (v == null) return false;
if (v == 1) count.remove(k);
else count.put(k, v - 1);
}
}
return true;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Hand of Straights interactively → ← All solutions