#914
X of a Kind in a Deck of Cards
EasyArrayHash TableMathCountingNumber TheoryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of checking each possible group size, we can use the greatest common divisor (GCD) of the frequencies of the cards. If the GCD is greater than 1, we can partition the deck into valid groups.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of each card in the deck.
- 2Step 2: Compute the GCD of all frequencies.
- 3Step 3: If the GCD is greater than 1, return true; otherwise, return false.
solution.py10 lines
1# Full working Python code
2from collections import Counter
3from math import gcd
4from functools import reduce
5
6def hasGroupsSizeX(deck):
7 count = Counter(deck)
8 freq = list(count.values())
9 overall_gcd = reduce(gcd, freq)
10 return overall_gcd > 1ℹ
Complexity note: The time complexity is O(n) because we count the frequencies in a single pass and compute the GCD in linear time relative to the number of unique card values.
- 1The problem can be reduced to finding the GCD of card frequencies.
- 2If the GCD is greater than 1, valid groupings are possible.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.