LeetEye LeetEye
Medium Greedy ~5 min

Hand of Straights

greedy hand-of-straights

Problem

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.

Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.

Examples

Example 1
Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
[1,2,3], [2,3,4], [6,7,8]
Example 2
Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Key Insight

Greedy: always start a group with the smallest available card.

Greedy: smallest card must start a group. Process sorted cards, form groups of consecutive numbers, decrement counts. Fail if any needed card is missing.

How to Approach This Problem

Pattern Recognition: When you see keywords like hand of straights greedy, think Greedy.

Step-by-Step Reasoning

1 If len(hand) % groupSize != 0:
Answer: Definitely impossible
Can't divide cards evenly into groups.
2 The smallest card must:
Answer: Start some group
No smaller card exists to have it continue a sequence. It must be a group's start.
3 Best data structure for this problem:
Answer: Hash map (count of each card)
Need to track how many of each card remain, efficiently check and decrement.
4 We should process cards:
Answer: In sorted order (smallest first)
Smallest must start a group. After using it, the next smallest becomes the new "must start".
5 When starting a group at card x:
Answer: Need exactly x, x+1, ..., x+groupSize-1
Consecutive means exactly x, x+1, x+2, etc.

Solution

def isNStraightHand(hand: List[int], groupSize: int) -> bool:
    if len(hand) % groupSize != 0:
        return False
    
    count = Counter(hand)
    
    for card in sorted(count):
        if count[card] > 0:  # Start a group
            need = count[card]
            # Need consecutive cards
            for i in range(groupSize):
                if count[card + i] < need:
                    return False
                count[card + i] -= need
    
    return True

Complexity Analysis

Time O(n log n)
Space O(n)

Master This Pattern

Build intuition with interactive MCQs. Practice Greedy problems in the LeetEye app.

Download LeetEye Free
Practice in LeetEye