Problem Description
Given an array of integers representing card values and a group size, determine if it is possible to rearrange the cards into groups where each group consists of consecutive cards of size equal to groupSize.
Key Insights
- The total number of cards must be divisible by groupSize.
- Use a frequency count (hash table or map) to record the occurrence of each card.
- Always start forming groups from the smallest available card to maintain the consecutive order.
- For each card, if its count is non-zero, check that the subsequent groupSize-1 cards exist with at least as many counts.
- Decrease the counts accordingly for each valid consecutive group.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the unique keys from the hand. Space Complexity: O(n) for storing the frequency count of the cards.
Solution
The solution uses a greedy approach along with a frequency hash map. The main steps are:
- Verify that the total number of cards is divisible by groupSize.
- Count the frequency of each card.
- Sort the keys of the frequency map.
- Iterate over the sorted keys and for each card with a positive count, try to form a group of groupSize consecutive cards.
- For each card in the group, decrease the frequency by the number of groups formed. If at any point the required card is missing or its count is insufficient, return false.
- If all groups can be formed successfully, return true.