Hand of Straights
MediumNeetCode 150 GreedyProblem
You hold a hand of cards, each with an integer value. You want to deal all the cards into groups of exactly
groupSize cards, where the values inside every group are consecutive
(such as 4, 5, 6).
Return true if the whole hand can be split this way, otherwise false.
Constraints
- 1 ≤ hand.length ≤ 10000
- 0 ≤ hand[i] ≤ 1000000000
- 1 ≤ groupSize ≤ hand.length
- card + groupSize stays below 2^31, so int is safe
Examples: pick one to animate
Solutions
TimeO(n log n + n · groupSize)
SpaceO(n)
Time: Sorting the distinct values costs n log n, and each card is removed from the counts once by one inner step.
Space: The count map holds up to n distinct cards.
The smallest card left can only be the start of a group. If it appears c times, c groups start there, so each of the next groupSize - 1 values must also have at least c copies. Remove those copies and move on to the next smallest card.