X of a Kind in a Deck of Cards

In this problem, we need to partition the cards into groups where each group contains cards with the same number and the size of each group is greater than 1.

One way to solve this problem is by using a dictionary to count the occurrences of each number in the deck and then checking if there is a common divisor greater than 1 for all the counts.

Python solution:

1
2
3
4
5
6
7
8
from collections import Counter
from math import gcd
from functools import reduce

class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        count = Counter(deck)
        return reduce(gcd, count.values()) >= 2

In this code:

  1. We import the necessary modules. Counter from collections is used to count the occurrences of each number in the deck, gcd from math is used to calculate the greatest common divisor, and reduce from functools is used to apply the gcd function to all values in the count dictionary.

  2. We define a method hasGroupsSizeX which takes a list deck as input and returns a boolean value.

  3. We create a Counter object for deck, which is a dictionary where the keys are the elements in deck and the values are the counts of their occurrences.

  4. We use the reduce function to apply the gcd function to all values in count. The reduce function applies a function of two arguments cumulatively to the items of an iterable, in this case count.values(), so as to reduce the iterable to a single output.

  5. We check if the greatest common divisor of all counts is greater than or equal to 2. If it is, we return True, indicating that it’s possible to partition the deck into groups where each group contains cards with the same number and the size of each group is greater than 1. If it’s not, we return False.