Visualize

Pattern visualizer

Hand of Straights

There is no real choice to make here, which is why one greedy pass settles it. Look at the smallest card still in hand: nothing smaller exists, so no group can ever place it in the middle or at the top of a run — it has to be the bottom of its own group, and that fixes the other cards that group needs. Take them if they exist; if any is missing the hand is impossible, because that smallest card had no other home to move to. Repeat and the hand either empties or contradicts itself. The duplicate 2 and 3 are the point: after 1,2,3 is spent the smallest card is 2 again, not 4, so the second group starts back down at 2. Animated on: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3. Can the whole hand be split into groups of 3 consecutive cards?.

The smallest card left is never free to choose

time O(n log n)space O(n)step 1 / 11
1
[0]
2
[1]
2
[2]
3
[3]
3
[4]
4
[5]
6
[6]
7
[7]
8
[8]
line 4

Sorted hand: 1, 2, 2, 3, 3, 4, 6, 7, 8. 9 cards and a group size of 3, so exactly 3 straights have to come out with nothing left over. Sorting is what makes "smallest card still in hand" cheap to ask, over and over.

Pseudocode
1FUNCTION isNStraightHand(hand, W)
2 IF LENGTH(hand) MOD W != 0
3 RETURN FALSE
4 count <- TALLY(hand)
5 WHILE SIZE(count) > 0
6 low <- MIN(KEYS(count))
7 FOR v <- low TO low + W - 1
8 IF count[v] = 0
9 RETURN FALSE
10 count[v] <- count[v] - 1
11 RETURN TRUE

← / → step · space play · Home restart

Where to practice Greedy