SDE & MLE Prep

846. Hand of Straights

Problem

Decide whether the cards in hand can be split into groups of groupSize cards whose values are consecutive (like 2, 3, 4).

Example: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 → true ([1,2,3], [2,3,4], [6,7,8])

Constraints: up to 10⁴ cards.

Always start a group at the smallest remaining card (it can't belong anywhere else). Consume x, x+1, …, x+k−1 from the counter.

Complexity: O(n log n).

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if len(hand) % groupSize:
            return False
        cnt = Counter(hand)
        for x in sorted(cnt):
            c = cnt[x]
            if c == 0:
                continue
            for y in range(x, x + groupSize):
                if cnt[y] < c:
                    return False
                cnt[y] -= c
        return True