Medium — Hash Table | Greedy | Sorting | Counting
The Problem
Determine if you can rearrange a hand of cards into groups where each group has exactly W cards forming consecutive sequences.
Approach
Use a counter to track card frequencies, then iterate through sorted cards and greedily form consecutive groups by checking if the next W consecutive cards are available. Decrement the counter for each card used in a group.
Time: O(n log n) · Space: O(n)
Code
from collections import Counter
class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
if len(hand) % W != 0:
return False
counter = Counter(hand)
hand.sort()
for card in hand:
if counter[card] > 0:
for i in range(W):
if counter[card + i] <= 0:
return False
counter[card + i] -= 1
return True
Watch It Run
Open interactive visualization
Try it yourself: Open TraceLit and step through every line.
Built with TraceLit — the visual algorithm tracer for LeetCode practice.

Top comments (0)