Determine if W cards can be rearranged into groups of groupSize consecutive cards.
Input: hand=[1,2,3,6,2,3,4,7,8], groupSize=3 → Output: true
Input: hand=[1,2,3,4,5], groupSize=4 → Output: false
Sort cards. Use a count map. For each smallest card, form a group by consuming consecutive cards.
- Count frequency of each card using TreeMap (sorted)
- While map is not empty: get smallest card x
- Try to form group x,x+1,...,x+groupSize-1
- If any card in group missing return false
- Decrement counts, remove zeros
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) return false;
TreeMap<Integer, Integer> count = new TreeMap<>();
for (int card : hand) count.merge(card, 1, Integer::sum);
while (!count.isEmpty()) {
int first = count.firstKey();
for (int i = 0; i < groupSize; i++) {
int c = first + i;
if (!count.containsKey(c)) return false;
count.merge(c, -1, Integer::sum);
if (count.get(c) == 0) count.remove(c);
}
}
return true;
}
- Time Complexity: O(n log n)
- Space Complexity: O(n)