PracticeNeetCode ↗LeetCode ↗
Given an array hand of card values and an integer groupSize, determine whether the cards can be rearranged into groups of exactly groupSize consecutive values, with no leftovers.
groupSize consecutive values from it.len(hand) isn't divisible by groupSize, it's immediately impossible — check that first.len(hand) % groupSize != 0, return False.groupSize consecutive values starting there, decrementing each one's count.False. Pop a value from the heap once its count hits zero. Return True once every card is consumed.Time: O(n log n) — Space: O(n)
from collections import Counter
import heapq
def isNStraightHand(hand: list[int], groupSize: int) -> bool:
if len(hand) % groupSize != 0:
return False
count = Counter(hand)
minHeap = list(count.keys())
heapq.heapify(minHeap)
while minHeap:
first = minHeap[0]
for card in range(first, first + groupSize):
if count[card] == 0:
return False
count[card] -= 1
if count[card] == 0:
if card != minHeap[0]:
return False
heapq.heappop(minHeap)
return TrueHow the solution above works, piece by piece.
groupSize, it can't be split → False.count holds how many of each card are left; a min-heap of distinct values gives the smallest card quickly.first, first+1, …. A missing card means failure.False.Running it on hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize = 3:
first, first+1, first+2 each time uses every card: [1, 2, 3], [2, 3, 4], [6, 7, 8].