846. Hand of Straights

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) {
return false;
}

TreeMap<Integer, Integer> countMap = new TreeMap<>();
for (int h : hand) {
countMap.put(h, countMap.getOrDefault(h, 0) + 1);
}
while (!countMap.isEmpty()) {
int start = countMap.firstKey();
for (int i = 0; i < groupSize; i++) {
int value = start + i;
Integer count = countMap.get(value);
if (count == null) {
return false;
} else {
if (count == 1) {
countMap.remove(value);
} else {
countMap.put(value, count - 1);
}
}
}
}

return true;
}
}

References

846. Hand of Straights
1296. Divide Array in Sets of K Consecutive Numbers