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.
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