LeetCode Solutions

914. X of a Kind in a Deck of Cards

Time:

Space:

			

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;
  }
};
			

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;
  }
}
			

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