X of a Kind in a Deck of Cards - Problem
You have a deck of cards, and each card has a number written on it. Your task is to determine if you can partition all the cards into groups where:
- Each group has exactly X cards (where X โฅ 2)
- All cards in the same group have the same number
- Every card must be placed in exactly one group
Return true if such a partition is possible, false otherwise.
Example: If you have cards [1,2,3,4,4,3,2,1], you could group them as:
- Group 1: [1,1] (2 cards with value 1)
- Group 2: [2,2] (2 cards with value 2)
- Group 3: [3,3] (2 cards with value 3)
- Group 4: [4,4] (2 cards with value 4)
Since all groups have the same size (2) and X=2 โฅ 2, this partition is valid!
Input & Output
example_1.py โ Basic valid partition
$
Input:
[1,2,3,4,4,3,2,1]
โบ
Output:
true
๐ก Note:
We can partition into groups of size 2: [1,1], [2,2], [3,3], [4,4]. Each group has exactly 2 cards with the same value.
example_2.py โ No valid partition
$
Input:
[1,1,1,2,2,2,3,3]
โบ
Output:
false
๐ก Note:
We have 3 ones, 3 twos, and 2 threes. No single group size X works for all: X=2 doesn't divide 3, X=3 doesn't divide 2.
example_3.py โ Single card type
$
Input:
[1,1,1,1,1,1]
โบ
Output:
true
๐ก Note:
All 6 cards have value 1. We can form 3 groups of size 2, or 2 groups of size 3, or 1 group of size 6. All are valid since X โฅ 2.
Visualization
Tap to expand
Understanding the Visualization
1
Count Players by Card
Count how many players have each card value - this gives us frequency constraints
2
Find Team Size
The team size must divide evenly into every card group - this is where GCD helps
3
Verify Minimum
Check if the largest valid team size is at least 2 players
4
Form Teams
If GCD โฅ 2, we can successfully partition all players into equal-sized teams
Key Takeaway
๐ฏ Key Insight: The problem reduces to finding GCD of frequencies. If GCD โฅ 2, we can partition all cards into equal-sized groups where each group contains cards of the same value.
Time & Space Complexity
Time Complexity
O(n log(max_freq))
Single pass O(n), with GCD computation O(log(max_freq)) for each unique card
โก Linearithmic
Space Complexity
O(k)
Hash map to store frequency of k unique card values
โ Linear Space
Constraints
- 1 โค deck.length โค 104
- 0 โค deck[i] < 104
- Group size must be at least 2
- All cards must be partitioned (no leftover cards allowed)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code