X of a Kind in a Deck of Cards

easy math gcd counting

Problem

You are given an integer array deck where deck[i] is the value written on the i-th card. Return true if and only if you can partition the cards into one or more groups such that each group has exactly the same number of cards X (with X ≥ 2) and every card in a group shows the same value.

Inputdeck = [1, 2, 3, 4, 4, 3, 2, 1]
Outputtrue
Each value appears exactly twice, so we can form four groups of size X = 2.

from collections import Counter
from math import gcd
from functools import reduce

def has_groups_size_x(deck):
    counts = Counter(deck).values()
    g = reduce(gcd, counts)
    return g >= 2
function hasGroupsSizeX(deck) {
  const counts = new Map();
  for (const c of deck) counts.set(c, (counts.get(c) || 0) + 1);
  const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
  let g = 0;
  for (const v of counts.values()) g = gcd(g, v);
  return g >= 2;
}
class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        Map<Integer, Integer> counts = new HashMap<>();
        for (int c : deck) counts.merge(c, 1, Integer::sum);
        int g = 0;
        for (int v : counts.values()) g = gcd(g, v);
        return g >= 2;
    }
    private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
bool hasGroupsSizeX(vector<int>& deck) {
    unordered_map<int, int> counts;
    for (int c : deck) counts[c]++;
    int g = 0;
    for (auto& p : counts) g = std::gcd(g, p.second);
    return g >= 2;
}
Time: O(n log V) Space: O(n)