LeetCode 914: X of a Kind in a Deck of Cards Solution

Master LeetCode problem 914 (X of a Kind in a Deck of Cards), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

914. X of a Kind in a Deck of Cards

Problem Explanation

Explanation

To solve this problem, we can use the concept of finding the greatest common divisor (GCD) of the counts of all unique integers in the array. If we can find a common divisor greater than 1, then it means we can partition the deck into groups with x cards each, where x is the GCD.

  1. Count the occurrences of each unique integer in the deck.
  2. Find the GCD of all these counts.
  3. If the GCD is greater than 1, return true; otherwise, return false.

Time Complexity:

  • Counting occurrences: O(n)
  • Finding GCD: O(log(min(counts)))

Space Complexity:

  • O(n) for storing the counts of unique integers

Solution Code

class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        Map<Integer, Integer> counts = new HashMap<>();
        for (int card : deck) {
            counts.put(card, counts.getOrDefault(card, 0) + 1);
        }
        
        int gcd = 0;
        for (int count : counts.values()) {
            gcd = gcd(gcd, count);
        }
        
        return gcd > 1;
    }
    
    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 914 (X of a Kind in a Deck of Cards)?

This page provides optimized solutions for LeetCode problem 914 (X of a Kind in a Deck of Cards) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 914 (X of a Kind in a Deck of Cards)?

The time complexity for LeetCode 914 (X of a Kind in a Deck of Cards) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 914 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 914 in Java, C++, or Python.

Back to LeetCode Solutions