Hand of Straights (LeetCode 846): Solution and Explanation
Given a hand of card values and a group size, decide whether you can split all the cards into groups of exactly that size, where each group is a run of consecutive values.
Watch it run step by step
Try your own input and write the code →Intuition
If the number of cards is not a multiple of the group size, the answer is immediately no. Beyond that, a brute force would try forming groups in different ways and backtrack on failure, which can be exponential. The useful question is whether some card's group is forced.
It is. Look at the smallest card value still in the hand. No group can contain a smaller value, so that card must be the first card of its run. Its group is therefore fully determined: it must contain the smallest value and the next groupSize - 1 consecutive values. If any of those values is missing, the hand cannot be split. Because this choice is forced, a greedy algorithm that always starts a run at the smallest remaining value is correct, not just a heuristic.
To make this efficient, store card counts in a hash map and keep the distinct values in a min-heap, so the smallest remaining value is always at the top. Forming a group decrements the count of each value in the run. When a value's count reaches zero, it should be removed from the heap, and it must be the current minimum. If a value in the middle of the run hits zero while a smaller value still has copies, those smaller copies can never start a run that skips this value, so the answer is false.
Approach: Greedy with counts and a min-heap
- Return false right away if
len(hand) % groupSizeis not zero. - Count how many times each card value appears.
- Put the distinct values into a min-heap
minH. - While the heap is not empty, let
first = minH[0]and try to build the run fromfirsttofirst + groupSize - 1. - For each value in the run, return false if it is missing, otherwise decrement its count.
- When a count reaches zero, it must equal
minH[0]; if so pop it, otherwise return false. - If the heap empties, every card was placed, so return true.
Step-by-step example
hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
- Nine cards split into groups of three, so the size check passes. Counts: 1:1, 2:2, 3:2, 4:1, 6:1, 7:1, 8:1. The heap holds [1,2,3,4,6,7,8].
- first = 1: the run is 1, 2, 3. Value 1 drops to 0 and is the heap top, so pop it. Values 2 and 3 drop to 1.
- first = 2: the run is 2, 3, 4. Each drops to 0 in order, and each is the heap top at that moment, so all three are popped.
- first = 6: the run is 6, 7, 8. All drop to 0 and are popped in order.
- The heap is empty, so return true. The groups are [1,2,3], [2,3,4] and [6,7,8].
Code: Python, Java, C++
1class Solution:
2 def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
3 if len(hand) % groupSize:
4 return False
5
6 count = {}
7 for n in hand:
8 count[n] = 1 + count.get(n, 0)
9
10 minH = list(count.keys())
11 heapq.heapify(minH)
12
13 while minH:
14 first = minH[0]
15 for i in range(first, first + groupSize):
16 if i not in count:
17 return False
18 count[i] -= 1
19 if count[i] == 0:
20 if i != minH[0]:
21 return False
22 heapq.heappop(minH)
23 return True1class Solution {
2 public boolean isNStraightHand(int[] hand, int groupSize) {
3 if (hand.length % groupSize != 0) return false;
4
5 TreeMap<Integer, Integer> count = new TreeMap<>();
6 for (int n : hand) count.put(n, count.getOrDefault(n, 0) + 1);
7
8 while (!count.isEmpty()) {
9 int first = count.firstKey();
10 for (int i = first; i < first + groupSize; i++) {
11 if (!count.containsKey(i)) return false;
12 int c = count.get(i);
13 if (c == 1) count.remove(i);
14 else count.put(i, c - 1);
15 }
16 }
17 return true;
18 }
19}1class Solution {
2public:
3 bool isNStraightHand(vector<int>& hand, int groupSize) {
4 if (hand.size() % groupSize != 0) return false;
5 map<int, int> count;
6 for (int n : hand) count[n]++;
7
8 while (!count.empty()) {
9 int first = count.begin()->first;
10 for (int i = first; i < first + groupSize; i++) {
11 if (!count.count(i)) return false;
12 count[i]--;
13 if (count[i] == 0) count.erase(i);
14 }
15 }
16 return true;
17 }
18};Time and space complexity
O(n log n)
Building the heap of distinct values is O(n), and each value is popped once at O(log n). Every card is decremented exactly once while forming groups, so the run-building work is O(n) overall.
O(n)
The count map and the heap each hold up to n distinct values.
Other approaches
Sort the distinct values (time O(n log n), space O(n))
Sort the keys of the count map and walk them in order. For each value with a positive count c, subtract c from the counts of the next groupSize - 1 values, failing if any would go negative. This handles many groups at once and avoids the heap.
Common mistakes
- Skipping the divisibility check. It is cheap and rules out many inputs before any real work.
- Starting a run from an arbitrary card instead of the smallest remaining one. Only the smallest value has a forced group, which is what makes the greedy choice safe.
- Popping a value from the heap when its count reaches zero without checking it is the minimum. If a smaller value still has copies, those cards can never be placed and the answer is false.
- Treating duplicates as a single card. Values like 2 and 3 can appear several times and each copy must go into a separate run.
Frequently asked questions
Why start each group at the smallest card?
Nothing smaller remains, so the smallest card cannot be in the middle or end of a run. It must begin one, which fixes the whole group and makes the greedy choice provably correct.
What is the time complexity of hand of straights?
It is O(n log n) because of the heap of distinct values. Every card is processed a constant number of times apart from the heap operations, and space is O(n).
Can you solve hand of straights without a heap?
Yes. Sort the distinct values once and process them in order, subtracting each value's count from the next groupSize - 1 values. This is also O(n log n) and often simpler.