The Runtime Theory
mediumleetcode#greedy#hash-map

Hand of Straights

Decide if a deck of cards can be regrouped into consecutive runs of equal size; greedy group building from each run's smallest card uses a frequency map.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

inhand = [1,2,3,6,2,3,4,7,8], groupSize = 3

outtrue

inhand = [1,2,3,4,5], groupSize = 4

outfalse

Given an array of card values and a group size, the machine must decide whether every card can be arranged into groups of consecutive increasing values, each group exactly the given size, with every card used exactly once. Values may repeat, and duplicates must land in different groups.

The key insight is that the smallest remaining card forces the start of a group. It cannot belong to any group that starts lower, because nothing lower remains, so it must begin a group spanning the next groupSize consecutive values. This makes the greedy choice deterministic rather than a guess.

The approach runs in three steps. First, count every card's frequency and reject immediately if the deck length is not divisible by the group size. Second, sort the unique values and walk them in ascending order. Third, for each value with remaining count, carve out full groups of consecutive values, decrementing frequencies and failing the moment any needed card is missing. Time is O(n log n) and space is O(n).

The trickiest edge case is a length that divides cleanly but values that do not chain: [1,2,3,4,5] with groupSize 4 fails because after grouping 1-4 the 5 is stranded. The machine must also drain duplicates within one group pass, which is why the while loop over the count exists.

python
from collections import Counter
 
def isNStraightHand(hand, groupSize):
    if len(hand) % groupSize:
        return False
    count = Counter(hand)
    for card in sorted(count):
        while count[card] > 0:
            for k in range(groupSize):
                if count.get(card + k, 0) == 0:
                    return False
                count[card + k] -= 1
    return True

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.