Leetcode 914. X of a Kind in a Deck of Cards
Given an array of integers deck
, where deck[i]
represents the ith card in the deck. Determine if we can partition the deck into one or more groups of cards, where:
X
cards.Return true
if and only if such a partition is possible.
Example:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1], [2,2], [3,3], [4,4]
deck
array?
X
that can divide all the frequencies perfectly, implying that the deck can be split into groups as required.#include <vector>
#include <unordered_map>
#include <algorithm>
#include <numeric>
class Solution {
public:
bool hasGroupsSizeX(std::vector<int>& deck) {
std::unordered_map<int, int> count;
for (int card : deck) {
count[card]++;
}
int gcd = -1;
for (auto& kv : count) {
if (gcd == -1) {
gcd = kv.second;
} else {
gcd = std::gcd(gcd, kv.second);
}
}
return gcd >= 2;
}
};
Overall, the time complexity is: [ O(N + K \log M) ]
This solution efficiently handles the problem constraints using standard algorithms for counting and computing the GCD.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?