groupSize cards.
Problem
Given an integer arrayhand representing cards and an integer groupSize, determine whether the cards can be rearranged into groups of groupSize consecutive cards.
Each card must be used exactly once. If the cards can be rearranged into valid groups, return
true; otherwise, return false.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
hand = [1, 2, 3, 6, 2, 3, 4, 7, 8]
groupSize = 3
Output
true
The cards can be rearranged into [1, 2, 3], [2, 3, 4], and [6, 7, 8].
Solution
This solution uses a TreeMap to store the frequency of each card. A Greedy approach is then used to build consecutive groups starting from the smallest available card.First, we count the frequency of every card. The TreeMap keeps the card values sorted, allowing us to always process the smallest available card first.
Whenever a card is still available, it must be the starting card of a new group. If the current card is
2 and groupSize is 3, we need the cards 2, 3, and 4.
If any required consecutive card does not have enough occurrences, we cannot form a valid group, so we return
false. Otherwise, we decrease the frequency of each card by the number of groups we are creating.
The Greedy approach works because the smallest available card must be used as the beginning of the next consecutive group. Otherwise, it would remain unused or create an invalid gap.
class Solution {
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.put(card, count.getOrDefault(card, 0) + 1);
}
for (int card : count.keySet()) {
int frequency = count.get(card);
if (frequency == 0) {
continue;
}
for (int i = 0; i < groupSize; i++) {
int current = card + i;
if (count.getOrDefault(current, 0) < frequency) {
return false;
}
count.put(current, count.get(current) - frequency);
}
}
return true;
}
}
Complexity
The time complexity isO(n log n) because the TreeMap maintains the cards in sorted order and each map operation takes O(log n) time.
The space complexity is
O(n) for storing the frequency of the cards in the TreeMap.
Comments
No comments yet. Ask a question or share what helped.