914. X of a Kind in a Deck of Cards LeetCode Solution
In this guide, you will get 914. X of a Kind in a Deck of Cards LeetCode Solution with the best time and space complexity. The solution to X of a Kind in a Deck of Cards problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- X of a Kind in a Deck of Cards solution in C++
- X of a Kind in a Deck of Cards solution in Java
- X of a Kind in a Deck of Cards solution in Python
- Additional Resources
Problem Statement of 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.
Example 1:
Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].
Example 2:
Input: deck = [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.
Constraints:
1 <= deck.length <= 104
0 <= deck[i] < 104
Complexity Analysis
- Time Complexity:
- Space Complexity:
914. X of a Kind in a Deck of Cards LeetCode Solution in C++
class Solution {
public:
bool hasGroupsSizeX(vector<int>& deck) {
unordered_map<int, int> count;
int gcd = 0;
for (const int d : deck)
++count[d];
for (const auto& [_, value] : count)
gcd = __gcd(gcd, value);
return gcd >= 2;
}
};
/* code provided by PROGIEZ */
914. X of a Kind in a Deck of Cards LeetCode Solution in Java
class Solution {
public boolean hasGroupsSizeX(int[] deck) {
Map<Integer, Integer> count = new HashMap<>();
int gcd = 0;
for (final int d : deck)
count.merge(d, 1, Integer::sum);
for (final int value : count.values())
gcd = __gcd(gcd, value);
return gcd >= 2;
}
private int __gcd(int a, int b) {
return b > 0 ? __gcd(b, a % b) : a;
}
}
// code provided by PROGIEZ
914. X of a Kind in a Deck of Cards LeetCode Solution in Python
class Solution:
def hasGroupsSizeX(self, deck: list[int]) -> bool:
count = collections.Counter(deck)
return functools.reduce(math.gcd, count.values()) >= 2
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.