X of a Kind in a Deck of Cards - 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
  • All the cards in one group have the same integer written on them

Return true if such partition is possible, or false otherwise.

Input & Output

Example 1 — Valid Grouping
$ Input: deck = [1,2,3,4,4,3,2,1]
Output: true
💡 Note: Each number appears exactly 2 times. We can group them as (1,1), (2,2), (3,3), (4,4) with group size 2.
Example 2 — Invalid Grouping
$ Input: deck = [1,1,1,2,2,2,3,3]
Output: false
💡 Note: Numbers 1,2,3 appear 3,2,1 times respectively. GCD(3,2,1) = 1, so no valid group size > 1 exists.
Example 3 — Single Card Type
$ Input: deck = [1,1,1,1,2,2,2,2,2,2]
Output: true
💡 Note: Number 1 appears 4 times, number 2 appears 6 times. GCD(4,6) = 2, so we can make groups of size 2.

Constraints

  • 1 ≤ deck.length ≤ 104
  • 0 ≤ deck[i] < 104

Visualization

Tap to expand
X of a Kind: Group Cards by Same Number12344321Input: [1,2,3,4,4,3,2,1](1,1)(2,2)(3,3)(4,4)Groups of size 2 (each number appears 2 times)Output: true
Understanding the Visualization
1
Input
Array of card numbers: [1,2,3,4,4,3,2,1]
2
Process
Count frequencies and find valid group size
3
Output
Boolean: true if valid grouping exists
Key Takeaway
🎯 Key Insight: Valid grouping exists if and only if GCD of all frequencies > 1
Asked in
Google 15 Amazon 12
64.5K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen