Hand of Straights - Problem
Card Sequence Challenge: Alice has a deck of cards with numbers written on them and wants to organize them into consecutive groups. Each group must contain exactly
Given an array
Example: If Alice has cards
groupSize cards with consecutive values (like 3,4,5 or 7,8,9,10).Given an array
hand where each element represents a card value, and an integer groupSize, determine if Alice can successfully arrange all her cards into valid consecutive groups.Example: If Alice has cards
[1,2,3,6,2,3,4,7,8] and groupSize = 3, she can form groups [1,2,3], [2,3,4], and [6,7,8] - so return true. Input & Output
example_1.py โ Basic Consecutive Groups
$
Input:
hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
โบ
Output:
true
๐ก Note:
Alice can form three groups: [1,2,3], [2,3,4], and [6,7,8]. Each group has exactly 3 consecutive cards.
example_2.py โ Impossible Grouping
$
Input:
hand = [1,2,3,4,5], groupSize = 4
โบ
Output:
false
๐ก Note:
We have 5 cards but need groups of size 4. Since 5 is not divisible by 4, it's impossible to form valid groups.
example_3.py โ Single Card Groups
$
Input:
hand = [1,1,2,2,3,3], groupSize = 1
โบ
Output:
true
๐ก Note:
When groupSize is 1, each card forms its own group. Any hand can be arranged this way.
Visualization
Tap to expand
Understanding the Visualization
1
Count All Cards
Create a frequency map to know how many of each card value we have
2
Sort Card Values
Process card values in ascending order to ensure optimal grouping
3
Greedy Group Formation
For each card value, form as many consecutive sequences as possible
4
Validate Completeness
Ensure all cards are used and all groups are properly formed
Key Takeaway
๐ฏ Key Insight: The greedy approach of always starting with the smallest available card is optimal because it never blocks better arrangements - if a valid grouping exists, the greedy method will find it.
Time & Space Complexity
Time Complexity
O(n log n)
O(n log n) for sorting + O(n log n) for priority queue operations
โก Linearithmic
Space Complexity
O(n)
Priority queue and additional data structures to track sequences
โก Linearithmic Space
Constraints
- 1 โค hand.length โค 104
- 0 โค hand[i] โค 109
- 1 โค groupSize โค hand.length
- All card values are non-negative integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code