Skip to content

914. X of a Kind in a Deck of Cards

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool hasGroupsSizeX(vector<int>& deck) {
    unordered_map<int, int> count;
    int gcd = 0;

    for (const int d : deck)
      ++count[d];

    for (const auto& [_, value] : count)
      gcd = __gcd(gcd, value);

    return gcd >= 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public boolean hasGroupsSizeX(int[] deck) {
    Map<Integer, Integer> count = new HashMap<>();
    int gcd = 0;

    for (final int d : deck)
      count.merge(d, 1, Integer::sum);

    for (final int value : count.values())
      gcd = __gcd(gcd, value);

    return gcd >= 2;
  }

  private int __gcd(int a, int b) {
    return b > 0 ? __gcd(b, a % b) : a;
  }
}
1
2
3
4
class Solution:
  def hasGroupsSizeX(self, deck: list[int]) -> bool:
    count = collections.Counter(deck)
    return functools.reduce(math.gcd, count.values()) >= 2