X of a Kind in a Deck of Cards — LeetCode 914 Python Solution

EasyArrayHash TableMathCountingNumber Theory
Problem
#914
Reading time
2 min

The problem

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.

Example

Input
deck = [1,2,3,4,4,3,2,1]
Output
true
Explanation
Possible partition [1,1],[2,2],[3,3],[4,4].

Python solution

Python
class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        cnt = Counter(deck)
        return reduce(gcd, cnt.values()) >= 2

Complexity

MeasureComplexity
TimeO(n \times \log M)
SpaceO(n + \log M) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 914. X of a Kind in a Deck of Cards is filed here because LeetCode tags it Math and Number Theory, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 914. X of a Kind in a Deck of Cards?
LeetCode 914. X of a Kind in a Deck of Cards is rated Easy on LeetCode.
What is the time complexity of LeetCode 914. X of a Kind in a Deck of Cards?
The Python solution on this page runs in O(n \times \log M).
What is the space complexity of LeetCode 914. X of a Kind in a Deck of Cards?
The Python solution on this page uses O(n + \log M) auxiliary space.
What topics does LeetCode 914. X of a Kind in a Deck of Cards cover?
LeetCode 914. X of a Kind in a Deck of Cards is tagged Array, Hash Table, Math, Counting and Number Theory on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview