Rummy Card Game
Rummy is a two-player card game played in a series of rounds. At the beginning of each round, each player is dealt a 10-card hand from a 36-card deck.
Each card in the deck is uniquely composed of the following two attributes:
One of 4 “suits” (Spades ‘S’, Hearts ‘H’, Clubs ‘C’, or Diamonds ‘D’) One of 9 “ranks” (the numbers 1-9)
The goal of the game is to group cards into groups (melds) of 3 or more cards of matching rank, which can either be:
- “sets”: 3+ cards of the same rank (ex: 9D, 9S, 9C since they all have rank 9)
- “runs”: 3+ cards of consecutive values within the same suit. Consecutive values are any values in the sequence of 1,2,3,4,5,6,7,8,9 (ex: 1-2-3-4 is consecutive, 1-2-4-5 is not).
Given an input of a hand of cards with suits and ranks, return all possible sets and runs that could be formed.
Example 1:
Example 2:
Notes
Intuition
Rummy melds are either sets (same rank, different suits) or runs (consecutive ranks, same suit). Group cards by rank and suit separately, then generate all valid combinations.
Implementation
Build two hashmaps: one grouping cards by rank, another by suit. For sets, find ranks with 3+ cards and generate all combinations of size 3, 4, etc. For runs, sort each suit's cards by rank, find consecutive segments, and generate all windows of size 3+ within each segment.
Edge-cases
After processing consecutive cards, there may be a final segment that didn't trigger the flush logic—handle it after the loop.
- Time: O(n²) — generating combinations; acceptable for small card counts
- Space: O(n²) — storing all possible melds