Count each card value and compute the greatest common divisor of all frequencies; a valid shared group size exists exactly when the gcd exceeds one.
Complexity
O(n + v log n) time and O(v) space for v distinct values.
Determine whether cards can be partitioned into equal-size groups of identical values with group size at least two.
Count each card value and compute the greatest common divisor of all frequencies; a valid shared group size exists exactly when the gcd exceeds one.
O(n + v log n) time and O(v) space for v distinct values.
package main
func hasGroupsSizeX(deck []int) bool {
counts := map[int]int{}
for _, card := range deck {
counts[card]++
}
gcd := func(a int, b int) int {
for b != 0 {
a, b = b, a%b
}
return a
}
divisor := 0
for _, count := range counts {
divisor = gcd(divisor, count)
}
return divisor >= 2
}
from collections import Counter
from functools import reduce
from math import gcd
class Solution:
def hasGroupsSizeX(self, deck: list[int]) -> bool:
return reduce(gcd, Counter(deck).values()) >= 2
function hasGroupsSizeX(deck: number[]): boolean {
const counts = new Map<number, number>(); for (const card of deck) counts.set(card, (counts.get(card) ?? 0) + 1);
const gcd = (a: number, b: number): number => b === 0 ? a : gcd(b, a % b);
let divisor = 0; for (const count of counts.values()) divisor = gcd(divisor, count);
return divisor >= 2;
}