Hand of Straights

Medium

Topics
ArrayGreedyHash TableSorting

Given an array hand of card values and a group size k (LeetCode: groupSize), return true if the cards can be rearranged into groups of k consecutive cards.

Example 1

102132632435467788
Input:  hand = [1,2,3,6,2,3,4,7,8], k = 3
Output: true

Example 2

1021324354
Input:  hand = [1,2,3,4,5], k = 4
Output: false

Constraints

  • 1 <= hand.length <= 10^4
  • 0 <= hand[i] <= 10^9
  • 1 <= k
Editorial — intuition, approach, complexity and pitfalls

Intuition

The smallest remaining card must start a group. Greedily forming groups from the smallest value forces the choice, so a frequency map processed in sorted order settles it.

Approach

  1. If the count of cards is not divisible by k, return false.
  2. Count each value; process values in ascending order.
  3. For each value with remaining count c, consume c copies of the next k consecutive values; if any is short, return false.

Dry Run

hand [1,2,3,6,2,3,4,7,8], groupSize 3
  len(hand) % 3 == 0, so a partition is at least conceivable
  counts {1:1, 2:2, 3:2, 4:1, 6:1, 7:1, 8:1}
  smallest card left is 1, with 1 copy  ->  must start 1 run of [1,2,3]
     counts now {2:1, 3:1, 4:1, 6:1, 7:1, 8:1}
  smallest card left is 2, with 1 copy  ->  must start 1 run of [2,3,4]
     counts now {6:1, 7:1, 8:1}
  smallest card left is 6, with 1 copy  ->  must start 1 run of [6,7,8]
     counts now empty
answer true
The smallest remaining card has no choice, and that is the entire argument. Nothing
below it exists, so it can only be the FIRST card of its run -- there is no
decision to make and therefore nothing to backtrack over.
Consuming c copies at once rather than one run at a time is the second trick. If
the smallest card appears twice, both copies must head their own runs, so both runs
can be removed in a single pass.
On [1,2,3,4,5] with groupSize 4 the length check already fails -- 5 is not divisible
by 4 -- and the answer is false before any counting happens.

Complexity

  • Time — O(n log n): sorting the distinct values.
  • Space — O(n): the count map.

Common Pitfalls

  • Start each group at the smallest available card; picking arbitrary starts fails.

Full Solution — all languages

class Solution:
    def isNStraightHand(self, hand, k):
        if len(hand)%k: return False
        from collections import Counter
        count=Counter(hand)
        for v in sorted(count):
            c=count[v]
            if c>0:
                for i in range(v,v+k):
                    if count[i]<c: return False
                    count[i]-=c
        return True
SensAI
Beta
Tap the mic to stop voice mode