Algorithms · Visualized
Hand of Straights
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Determines if a hand of cards can be rearranged into groups of consecutive numbers of a given size W. Time: O(n log n) average, O(n log n) worst; space: O(n) — frequency map.
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Hand of Straights
GreedyDetermines if a hand of cards can be rearranged into groups of consecutive numbers of a given size W. The greedy approach: always start a new group with the smallest remaining card, and greedily grab the next W-1 consecutive values to complete that group.
How Hand of Straights Works
- Count how many of each card value exist (a frequency map), and if the total number of cards isn't divisible by W, immediately fail.
- Repeatedly find the smallest value that still has a remaining count greater than 0.
- Try to form a group of W consecutive values starting from that smallest value, decrementing each value's count as you use it.
- If at any point one of the needed consecutive values has a count of 0, the hand cannot be grouped — fail.
- Continue forming groups from the smallest remaining card until all cards are used up — if you succeed, the hand can be grouped.
Hand of Straights Worked Example
Input: {hand: [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize: 3}
Counts: 1:1,2:2,3:2,4:1,6:1,7:1,8:1. Smallest remaining=1 → form group [1,2,3], decrement counts (2:1,3:1). Smallest remaining=2 → form group [2,3,4], decrement (3:0,4:0). Smallest remaining=6 → form group [6,7,8]. All counts now zero — success, groups: [1,2,3],[2,3,4],[6,7,8].
from collections import Counter
def hand_of_straights(hand, group_size):
cnt = Counter(hand)
for v in sorted(cnt):
if cnt[v] > 0:
need = cnt[v]
for x in range(v, v + group_size):
if cnt[x] < need:
return False
cnt[x] -= need
return TrueBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Hand of Straights Time & Space Complexity
When to Use Hand of Straights
- Card and tile games (like Rummy) needing to validate/organize consecutive-run groupings.
- Scheduling consecutive time-slot bundles from available resource counts.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.