X Of A Kind In A Deck Of Cards Problem
Description
LeetCode Problem 914.
In a deck of cards, each card has an integer written on it.
Return true if and only if you can choose X >= 2 such that it is possible to split the entire deck into 1 or more groups of cards, where:
- Each group has exactly X cards.
- All the cards in each group have the same integer.
Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
Example 2:
Input: deck = [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.
Example 3:
Input: deck = [1]
Output: false
Explanation: No possible partition.
Example 4:
Input: deck = [1,1]
Output: true
Explanation: Possible partition [1,1].
Example 5:
Input: deck = [1,1,2,2,2,2]
Output: true
Explanation: Possible partition [1,1],[2,2],[2,2].
Constraints:
- 1 <= deck.length <= 10^4
- 0 <= deck[i] < 10^4
Solution
Approach: Count, Then Take the GCD
Only how many times each number appears matters. Every group holds X cards of a single number, so a number that appears count times must be split into count / X full groups. That works exactly when X divides count.
So we need an X >= 2 that divides every count. The largest number dividing all counts is their greatest common divisor, and any other common divisor is a divisor of it. Therefore a valid X exists if and only if gcd(all counts) >= 2.
- Count each number in the deck with a hash map.
- Fold the counts with
gcd, starting from0(sincegcd(0, c) = c). - Return whether the result is at least
2.
A common mistake is to use the smallest count as X. With counts 4 and 6, the smallest count 4 does not divide 6, yet X = 2 works. The gcd catches this.
Example: deck = [1, 1, 2, 2, 2, 2] has counts 2 and 4, gcd = 2, so the answer is true.
Complexity: O(n log n) time in the worst case, where n is the length of deck: counting is O(n), and each gcd step takes O(log n). O(n) space for the counts.
import collections
import math
class Solution:
def hasGroupsSizeX(self, deck: List[int]) -> bool:
counts = collections.Counter(deck)
# A group size X works only if it divides every count, so the best X is their gcd.
group_size = 0
for count in counts.values():
group_size = math.gcd(group_size, count)
return group_size >= 2
Now write it from memory
Close the write-up and solve it yourself against the tests.