Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

914. X of a Kind in a Deck of Cards - Leetcode Solution

Code Implementation

from collections import Counter
from math import gcd
from functools import reduce

class Solution:
    def hasGroupsSizeX(self, deck):
        counts = Counter(deck).values()
        return reduce(gcd, counts) >= 2
      
#include <vector>
#include <unordered_map>
#include <numeric>
using namespace std;

class Solution {
public:
    bool hasGroupsSizeX(vector<int>& deck) {
        unordered_map<int, int> count;
        for (int card : deck) count[card]++;
        int g = 0;
        for (auto& p : count) g = gcd(g, p.second);
        return g >= 2;
    }
};
      
import java.util.*;
class Solution {
    public boolean hasGroupsSizeX(int[] deck) {
        Map<Integer, Integer> count = new HashMap<>();
        for (int card : deck)
            count.put(card, count.getOrDefault(card, 0) + 1);
        int g = 0;
        for (int val : count.values())
            g = gcd(g, val);
        return g >= 2;
    }
    private int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }
}
      
var hasGroupsSizeX = function(deck) {
    const count = {};
    for (let card of deck) count[card] = (count[card] || 0) + 1;
    const values = Object.values(count);
    const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
    let g = values[0];
    for (let v of values) g = gcd(g, v);
    return g >= 2;
};
      

Problem Description

You are given a list of integers deck representing a deck of cards, where each integer represents a card's value. Your task is to determine if it is possible to group the entire deck into one or more groups such that:

  • Each group has exactly X cards, where X >= 2.
  • All cards in a group have the same integer value.
  • Each card must belong to exactly one group (no reuse of cards).

Return true if such a grouping is possible, otherwise return false.

Thought Process

To tackle this problem, let's first consider what it means to group cards as described. We need to partition the deck into groups of size X (with X >= 2) where every group contains only cards of the same value. This means that for each unique card value, the quantity of that card in the deck must be divisible by X.

A brute-force approach would try every possible group size X (from 2 up to the size of the deck) and check if all counts are divisible by X. However, this is inefficient. Instead, we can observe that the largest possible group size X is the greatest common divisor (GCD) of all card counts. If the GCD is at least 2, then we can partition the deck as required. This insight leads us to a much more efficient solution.

Solution Approach

  • Count Occurrences: First, we count how many times each card value appears in the deck. This can be done efficiently with a hash map or dictionary.
  • Find GCD of Counts: Next, we compute the GCD of all these counts. The GCD represents the largest group size X such that every count is divisible by X.
  • Check GCD Constraint: If the GCD is at least 2, then it is possible to split the deck into groups of size X = GCD as required. If not, grouping is impossible.

We use a hash map for counting because it allows constant-time insertion and lookup. The GCD computation can be done efficiently by iteratively applying the GCD function to the list of counts.

Example Walkthrough

Let's consider the input deck = [1,2,3,4,4,3,2,1].

  • Count of each value: 1 appears 2 times, 2 appears 2 times, 3 appears 2 times, 4 appears 2 times.
  • List of counts: [2, 2, 2, 2]
  • GCD of [2, 2, 2, 2] is 2.
  • Since GCD is 2 (which is >= 2), we can group the deck into 4 groups of 2 cards each, where each group contains cards of the same value.
  • Thus, the function returns true.

If the deck was [1,1,1,2,2,2,3,3], the counts would be [3,3,2]. The GCD of 3,3,2 is 1, which is less than 2, so the answer is false.

Time and Space Complexity

  • Brute-force Approach: For each possible group size X from 2 to N (deck size), check if all counts are divisible by X. This is O(N^2) in the worst case.
  • Optimized Approach:
    • Counting occurrences takes O(N) time and O(N) space.
    • Computing the GCD of all counts takes O(K) time, where K is the number of unique card values (at most N).
    • Total time complexity: O(N).
    • Space complexity: O(N) for the count map.

Summary

The key insight of this problem is recognizing that the possibility of grouping depends on the greatest common divisor of the card counts. By counting occurrences and computing the GCD, we can efficiently determine if the deck can be partitioned as required. This approach is both elegant and efficient, reducing a potentially complex problem to a simple mathematical check.