846. Hand of Straights
Problem
Decide whether the cards in hand can be split into groups of groupSize cards whose values are consecutive (like 2, 3, 4).
Example: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3 → true ([1,2,3], [2,3,4], [6,7,8])
Constraints: up to 10⁴ cards.
Always start a group at the smallest remaining card (it can't belong anywhere else). Consume x, x+1, …, x+k−1 from the counter.
Complexity: O(n log n).
class Solution:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize:
return False
cnt = Counter(hand)
for x in sorted(cnt):
c = cnt[x]
if c == 0:
continue
for y in range(x, x + groupSize):
if cnt[y] < c:
return False
cnt[y] -= c
return True
assert Solution().isNStraightHand([1, 2, 3, 6, 2, 3, 4, 7, 8], 3) is True
assert Solution().isNStraightHand([1, 2, 3, 4, 5], 4) is False
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) return false;
TreeMap<Integer, Integer> cnt = new TreeMap<>();
for (int x : hand) cnt.merge(x, 1, Integer::sum);
for (int x : new ArrayList<>(cnt.keySet())) {
int c = cnt.get(x);
if (c == 0) continue;
for (int y = x; y < x + groupSize; y++) {
int have = cnt.getOrDefault(y, 0);
if (have < c) return false;
cnt.put(y, have - c);
}
}
return true;
}
}
func isNStraightHand(hand []int, groupSize int) bool {
if len(hand)%groupSize != 0 {
return false
}
cnt := map[int]int{}
for _, x := range hand {
cnt[x]++
}
keys := make([]int, 0, len(cnt))
for x := range cnt {
keys = append(keys, x)
}
sort.Ints(keys)
for _, x := range keys { // the smallest card left must start a group
c := cnt[x]
if c == 0 {
continue
}
for y := x; y < x+groupSize; y++ {
if cnt[y] < c {
return false
}
cnt[y] -= c
}
}
return true
}