Hand of Straights (LeetCode 846): Solution and Explanation

Medium
Array
Hash Table
Greedy
Sorting
Heap

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Return false right away if len(hand) % groupSize is not zero.
  2. Count how many times each card value appears.
  3. Put the distinct values into a min-heap minH.
  4. While the heap is not empty, let first = minH[0] and try to build the run from first to first + groupSize - 1.
  5. For each value in the run, return false if it is missing, otherwise decrement its count.
  6. When a count reaches zero, it must equal minH[0]; if so pop it, otherwise return false.
  7. 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
  1. 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].
  2. 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.
  3. 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.
  4. first = 6: the run is 6, 7, 8. All drop to 0 and are popped in order.
  5. 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 True

Time and space complexity

Time

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.

Space

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.