Digit Hand Showdown
Data Structure DesignAuto-graded · 23 test casesLast updated
Classify numeric hands by frequency patterns with custom ranking, then break ties using positional comparison without sorting.
You are building a card game simulator where each hand consists of five numeric cards. Cards are represented by digits 1 through 9, and duplicates are allowed.
Your task is to determine the winner between two hands.
Hand Categories
Hands are classified by the frequency distribution of their digits (how many times each digit appears). Categories are ranked from strongest to weakest:
- Five of a kind — all five digits are the same
- Four of a kind — four digits match
- Full house — three of one digit and two of another
- Two pair — two different pairs plus one unmatched digit
- Three of a kind — three matching digits
- One pair — exactly two matching digits
- High card — all digits are different
Comparison Rules
- First, classify both hands by category. The hand with the stronger category wins.
- If both hands belong to the same category, compare them position by position from right to left (starting at index 4, then 3, 2, 1, 0).
- At the first position where the digits differ, the hand with the larger digit wins.
- If all positions match, the hands are tied.
- Important: Do not reorder the digits before comparing positions. Use the original order given.
Return Value
Return 1 if the first hand wins, 2 if the second hand wins, or 0 if they tie.
Implementation Requirement
Use an object-oriented design with separate evaluator classes for each category. The solution should be extensible: adding a new category should require only creating a new evaluator class and registering it, without modifying the comparison logic.
Constraints
- Each hand is exactly 5 characters long
- All characters are digits from
'1'to'9' - 1 ≤ number of test cases ≤ 1000
Examples
Example 1
Input: compare_hands('33322', '99987')
Output: 1
Hints
Hint 1
Each category corresponds to a specific sorted frequency pattern. For instance, [2, 2, 1] represents two pair.
Hint 2
Check categories in order from strongest to weakest. Some patterns might match multiple categories, so the first match determines the classification.
Hint 3
For the positional tie-break, use Python's reversed() to walk the hands backward without modifying them.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution separates hand evaluation into two independent stages: category classification and positional tie-breaking.
Category classification: Count how many times each digit appears in the hand, producing a frequency list. The pattern of these frequencies determines the category. For example, frequencies [3, 2] indicate a full house (three of one digit, two of another), while [2, 2, 1] represents two pair.
We define one evaluator class per category, each with a numeric rank and a matches predicate that tests whether a frequency pattern belongs to that category. Categories are stored in a registry ordered from strongest to weakest. To classify a hand, we test each evaluator in sequence and return the rank of the first match.
Some predicates are intentionally simple. For instance, ThreeOfAKind checks only whether 3 appears in the frequency list, which is also true for full house. This works correctly because FullHouse appears earlier in the registry and catches full houses first. The registry order is critical to correctness.
Tie-breaking: When both hands share the same category rank, we compare their original digits position by position from right to left (index 4 down to 0). At the first position where digits differ, the larger digit wins. If no position differs, the hands are identical and we return a tie.
Crucially, we do not sort or reorder the hands before this comparison. The problem specifies using the original positions exactly as given.
Extensibility: To add a new category (for example, if the game expands to six-card hands with a "three pair" pattern), you write one new evaluator class, assign it a rank, and insert it into the registry at the appropriate position. The comparison function requires no changes.
Why It Works
Every five-digit hand with values 1–9 produces a unique frequency pattern that matches exactly one category when tested in registry order. The seven patterns listed cover all possible ways to partition five cards.
The right-to-left positional comparison respects the specification's requirement to preserve original order. Character comparison works correctly because all digits are single characters '1' through '9', so lexicographic order matches numeric order.
Complexity
Time: O(n) per comparison, where n = 5. Counting frequencies is O(n), classification tests at most 7 evaluators over at most 5 frequencies, and the tie-break iterates at most n positions. With fixed sizes, this simplifies to O(1).
Space: O(1). The frequency counter holds at most 5 distinct keys, and the evaluator objects are stateless.
Solution Code
from collections import Counter
class CategoryEvaluator:
"""Base class for hand category evaluators."""
rank = 0
def matches(self, counts):
raise NotImplementedError
class FiveOfAKind(CategoryEvaluator):
rank = 7
def matches(self, counts):
return 5 in counts
class FourOfAKind(CategoryEvaluator):
rank = 6
def matches(self, counts):
return 4 in counts
class FullHouse(CategoryEvaluator):
rank = 5
def matches(self, counts):
return sorted(counts) == [2, 3]
class TwoPair(CategoryEvaluator):
rank = 4
def matches(self, counts):
return sorted(counts) == [1, 2, 2]
class ThreeOfAKind(CategoryEvaluator):
rank = 3
def matches(self, counts):
return 3 in counts
class OnePair(CategoryEvaluator):
rank = 2
def matches(self, counts):
return 2 in counts
class HighCard(CategoryEvaluator):
rank = 1
def matches(self, counts):
return True
EVALUATORS = [FiveOfAKind, FourOfAKind, FullHouse, TwoPair,
ThreeOfAKind, OnePair, HighCard]
def classify_hand(hand):
"""Determine the category rank of a hand."""
counts = list(Counter(hand).values())
for evaluator_class in EVALUATORS:
evaluator = evaluator_class()
if evaluator.matches(counts):
return evaluator.rank
def compare_hands(hand1: str, hand2: str) -> int:
rank1 = classify_hand(hand1)
rank2 = classify_hand(hand2)
if rank1 != rank2:
return 1 if rank1 > rank2 else 2
# Same category: compare digits right to left
for digit1, digit2 in zip(reversed(hand1), reversed(hand2)):
if digit1 != digit2:
return 1 if digit1 > digit2 else 2
return 0