Categories:

Tags:



Problem

You are given an integer array deck where deck[i] represents the number written on the ith card.

Partition the cards into one or more groups such that:

  • Each group has exactly x cards where x > 1, and
  • All the cards in one group have the same integer written on them.

Return true if such partition is possible, or false otherwise.

Constraints

  • 1 <= deck.length <= 104
  • 0 <= deck[i] < 104

Solution

The problem X of a Kind in a Deck of Cards can be solved by counting the number of occurrences for each elements in the given array and checking if the greatest common divisor for the number of occurrences is greater than 1.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    int calculate_gcd(int num1, int num2)
    {
        if (num2 == 0)
            return num1;

        return calculate_gcd(num2, num1 % num2);
    }

    bool hasGroupsSizeX(vector<int> &deck)
    {
        unordered_map<int, int> hashmap;
        for (int &card : deck)
            hashmap[card] += 1;

        int gcd = 0;
        for (auto &[key, val] : hashmap)
            gcd = calculate_gcd(val, gcd);

        return gcd > 1;
    }
};