[LeetCode] X of a Kind in a Deck of Cards

914. X of a Kind in a Deck of Cards

You are given an integer array deck where deck[i] represents the number written on the ith card.

Partition the cards into one or more groups such that:

  • Each group has exactly x cards where x > 1, and
  • All the cards in one group have the same integer written on them.

Return true if such partition is possible, or false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> freq;
int g = deck.size();
for(int i = 0; i < deck.size(); i++) {
freq[deck[i]]++;
}
for(auto& [k,v] : freq) {
g = __gcd(g,v);
}
return g != 1;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> freq;
unordered_set<int> us;
for(int i = 0; i < deck.size(); i++) {
freq[deck[i]]++;
if(deck.size() % (i + 1) == 0 and i) us.insert(i+1);
}
for(auto& [k,v] : freq) {
unordered_set<int> uus;
for(auto x : us) {
if(v % x == 0) uus.insert(x);
}
swap(us,uus);
}
return us.size();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/09/PS/LeetCode/x-of-a-kind-in-a-deck-of-cards/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.