DEV Community

tracelit
tracelit

Posted on • Originally published at tracelit.dev

LeetCode 846: Hand Of Straights — Step-by-Step Visual Trace

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
Enter fullscreen mode Exit fullscreen mode

Watch It Run

Watch the algorithm run step by step

Watch the algorithm run step by step

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)