Example 1
- Input
- hand = [1, 2, 3, 6, 2, 3, 4, 7, 8], groupSize = 3
- Output
- true
The hand splits into [1,2,3], [2,3,4], and [6,7,8].
Given card values and a group size, decide whether the hand splits into groups of that size where each group holds consecutive values. Every card must be used exactly once.
Alice holds cards with values hand[i] and wants groups of exactly groupSize cards where each group is a run of consecutive values. Return true when the whole hand splits into such groups, and false otherwise.
For hand = [1, 2, 3, 6, 2, 3, 4, 7, 8] with groupSize = 3 the answer is true via [1,2,3], [2,3,4], and [6,7,8]. For hand = [1, 2, 3, 4, 5] with groupSize = 4 the answer is false because five cards cannot fill groups of four.
1 <= hand.length <= 10^40 <= hand[i] <= 10^91 <= groupSize <= hand.lengthThe hand splits into [1,2,3], [2,3,4], and [6,7,8].
Each group would use four cards, but five is not a multiple of four. One card would remain regardless of the arrangement, so return false.
The size is divisible by three, but both copies of the smallest value 1 must start [1,2,3]. There are two copies of 2 and only one 3, so the second group cannot be completed. The 4 cannot replace the missing 3.
A group of size one is already a consecutive run. The single card forms [0], so every card is used exactly once.
Imagine laying the remaining cards in sorted order. The smallest remaining value cannot appear after another card in a group: that would require an even smaller remaining value. It must start a run. In Example 1, the only 1 forces [1,2,3]; the remaining 2 then forces [2,3,4]. Duplicate values are separate cards, so overlapping runs are allowed but reusing a card is not. This forced-start rule lets us make a greedy choice without guessing between partitions.
Reveal Sort And Rescan: intuition, complexity, and code
groupSize = 1 always succeeds; [0] is the smallest allowed hand.[1,1,2,2,3,3] with size three succeed by creating two groups at once in the count sweep.[1,1,2,2,3,4] with size three lacks the second 3.[1,2,7,8] with size two succeeds; a gap inside a forced group fails.10^9 still require exact successors. A hand of repeated 10^9 values fails for size two; there is no wraparound successor.[1,1,2,2,3,3] needs two copies of every member.need before consuming any member.[1,2,2].10 before 2; always supply (a, b) => a - b.When items must form consecutive runs, the remaining minimum dictates the next group, so count frequencies and build upward from it.