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 (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 (int d : deck)
      count.put(d, count.getOrDefault(d, 0) + 1);

    for (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 = Counter(deck)
    return functools.reduce(math.gcd, count.values()) >= 2