File: x-of-a-kind-in-a-deck-of-cards/solution.py

Date: 2026-06-06

Time: 19:42

Purpose

This file solves LeetCode 914: X of a Kind in a Deck of Cards. It determines whether a deck of cards can be partitioned into groups where every group has the same size x >= 2 and all cards within each group share the same integer label.

Key Components

Solution.hasGroupsSizeX(self, deck: list[int]) -> bool

The single method. Its contract: given a list of integer card labels, return True if there exists some x >= 2 such that the deck can be split into groups of exactly x cards, each group containing only one distinct value.

Patterns

Reduce-to-GCD idiom. Rather than trying every possible group size, the solution exploits the mathematical insight that a valid x exists if and only if the GCD of all card counts is at least 2. This is a common competitive-programming reduction — transforming a search problem into a single arithmetic operation.

The pipeline is functional-style: Counter.values()reduce(gcd, ...) → threshold check. No mutation, no intermediate variables.

Dependencies

Imports:

Imported by: The corresponding x-of-a-kind-in-a-deck-of-cards/test_solution.py exercises this solution. The massive "Imported By" list in the prompt is an artifact of the repo's test infrastructure — those test files don't actually import *this* solution; they share a common test harness pattern.

Flow

1. Counter(deck) counts how many times each integer appears. For [1,1,2,2,2,2], this yields {1: 2, 2: 4}.

2. .values() extracts just the counts: [2, 4].

3. reduce(gcd, counts) folds pairwise GCD across all counts: gcd(2, 4) = 2.

4. The result is compared >= 2. If the GCD is at least 2, every count is divisible by that GCD, so groups of that size work.

Invariants

Error Handling

None. The solution trusts the LeetCode input contract (non-empty list of integers). An empty deck would crash at reduce with no initial value. This is appropriate for a competitive-programming solution operating under guaranteed constraints.

Topics to Explore

Beliefs