If all card counts have a common divisor greater than 1, we can partition the deck into groups of that size. The problem reduces to checking if the greatest common divisor (GCD) of all card counts is at least 2.
#include<numeric>classSolution {
public:bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> cnt;
for (int x : deck) cnt[x]++;
int ans =0;
for (auto& [k, v] : cnt) ans = gcd(ans, v);
return ans >=2;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
funcgcd(a, bint) int {
forb!=0 {
a, b = b, a%b }
returna}
funchasGroupsSizeX(deck []int) bool {
cnt:=map[int]int{}
for_, x:=rangedeck {
cnt[x]++ }
ans:=0for_, v:=rangecnt {
ans = gcd(ans, v)
}
returnans>=2}
1
2
3
4
5
6
7
8
9
10
11
12
13
import java.util.*;
classSolution {
publicbooleanhasGroupsSizeX(int[] deck) {
Map<Integer, Integer> cnt =new HashMap<>();
for (int x : deck) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
int ans = 0;
for (int v : cnt.values()) ans = gcd(ans, v);
return ans >= 2;
}
privateintgcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funhasGroupsSizeX(deck: IntArray): Boolean {
val cnt = deck.groupingBy { it }.eachCount().values
var ans = 0for (v in cnt) ans = gcd(ans, v)
return ans >=2 }
privatefungcd(a: Int, b: Int): Int = if (b ==0) a else gcd(b, a % b)
}
1
2
3
4
5
6
7
8
9
from typing import List
from math import gcd
from functools import reduce
classSolution:
defhasGroupsSizeX(self, deck: List[int]) -> bool:
from collections import Counter
vals = Counter(deck).values()
ans = reduce(gcd, vals)
return ans >=2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::collections::HashMap;
impl Solution {
pubfnhas_groups_size_x(deck: Vec<i32>) -> bool {
letmut cnt = HashMap::new();
for x in deck { *cnt.entry(x).or_insert(0) +=1; }
letmut ans =0;
for&v in cnt.values() { ans = gcd(ans, v); }
ans >=2 }
}
fngcd(mut a: i32, mut b: i32) -> i32 {
while b !=0 {
let t = b;
b = a % b;
a = t;
}
a
}