Ranking Five-Digit Card Hands with Pluggable Rules
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
In a custom numeric card game, each hand is represented as a 5-character string of digits from '1' through '9'. Because cards are drawn with replacement rather than from a standard suited deck, any digit may appear up to five times in a single hand.
Implement:
def compare_hands(hand1: str, hand2: str) -> int:
Return 1 when hand1 beats hand2, 2 when hand2 beats hand1, or 0 when both hands are tied.
Hands are judged by two sequential rules:
-
Category hierarchy (strongest to weakest): Every hand falls into one of seven categories determined strictly by how often its distinct digits repeat (suits, flushes, and straights play no role):
- Five of a kind — all five slots hold the same digit (shape
[5]) - Four of a kind — four matching digits plus one singleton (shape
[4, 1]) - Full house — three of one digit and two of another (shape
[3, 2]) - Two pair — two distinct pairs plus one singleton (shape
[2, 2, 1]) - Three of a kind — three matching digits plus two distinct singletons (shape
[3, 1, 1]) - One pair — one pair plus three distinct singletons (shape
[2, 1, 1, 1]) -
High card — five distinct digits (shape
[1, 1, 1, 1, 1])Notice that Two pair ranks above Three of a kind in this hierarchy.
- Five of a kind — all five slots hold the same digit (shape
-
Right-to-left positional tie-breaker: Whenever both hands belong to the same category, leave both strings in their original dealt order (never sort or group digits) and scan indices from right (
4) to left (0). At the first index where the two characters differ, the larger digit wins. If all five positions match, return0.
Structure your category checks behind a clean object-oriented evaluator interface so new hand rules can be plugged into the ranking list without altering the core comparator.
Examples
Example 1
compare_hands("88852", "44661")
# -> 2
Walk-through: "88852" has digit frequencies [3, 1, 1] (Three of a kind), whereas "44661" has digit frequencies [2, 2, 1] (Two pair). Because Two pair outranks Three of a kind under the custom hierarchy, hand2 wins (2) regardless of "88852" holding larger digits.
Example 2
compare_hands("25774", "77254")
# -> 1
Walk-through: Both strings contain one pair of '7's and singletons '2', '5', '4', placing both in One pair ([2, 1, 1, 1]). Scanning from rightmost index 4 leftward: index 4 ties ('4' vs '4'), and at index 3 hand1 has '7' while hand2 has '5'. Since 7 > 5, hand1 wins (1).
Example 3
compare_hands("61619", "61619")
# -> 0
Walk-through: Both hands are Two pair ([2, 2, 1]) and have identical digits at every position from index 4 down to index 0, resulting in a tie (0).
Constraints
len(hand1) == 5andlen(hand2) == 5.- Every character of
hand1andhand2is a digit from'1'to'9'inclusive.
Step-by-step walkthrough
Understand the custom ranking and tie-break rules
We are given two 5-character strings (
hand1andhand2) made of digits'1'through'9', and we return1ifhand1wins,2ifhand2wins, or0if they tie.Read the game rules carefully, because three details intentionally differ from standard poker:
- Five of a kind exists: digits are not limited to 4 suits, so
"11111"is valid and is the strongest category. - Custom category order: from strongest to weakest, the categories are:
Five of a kind>Four of a kind>Full house>Two pair>Three of a kind>One pair>High card. NoticeTwo pairoutranksThree of a kind! - Right-to-left positional tie-break: when both hands land in the same category, we do not sort the digits or compare pair ranks first. Instead, we compare the untouched strings starting from the rightmost position (
index 4) down to the leftmost position (index 0), and the larger digit at the first differing slot wins.
Finally, we want pluggable rule classes so future hand categories can be inserted into the ranking list while leaving the core comparator untouched.
- Five of a kind exists: digits are not limited to 4 suits, so
Summarize any hand by its multiplicity shape
A digit's multiplicity simply means how many times that digit appears in the 5-card hand. Because category membership depends only on multiplicities (not on which digits were used), sorting the digit frequencies from largest to smallest produces a unique shape for all 7 categories:
Category Example hand Digit counts Sorted shape ---------------- ------------- ---------------------- --------------- Five of a kind "77777" {'7': 5} [5] Four of a kind "91999" {'9': 4, '1': 1} [4, 1] Full house "55588" {'5': 3, '8': 2} [3, 2] Two pair "44661" {'4': 2, '6': 2, '1':1} [2, 2, 1] Three of a kind "88852" {'8': 3, '5': 1, '2':1} [3, 1, 1] One pair "25774" {'7': 2, ...} [2, 1, 1, 1] High card "12345" all 1s [1, 1, 1, 1, 1]Those seven shapes are all possible ways positive integers can add up to
5, so every 5-digit hand matches exactly one shape. Checking the whole shape (counts == [3, 2]vscounts == [3, 1, 1]) also prevents misclassifying a full house as three of a kind.from typing import Dict, List def compute_multiplicities(hand: str) -> List[int]: """Count how many times each digit appears, sorted largest first: '55588' -> [3, 2].""" digit_counts: Dict[str, int] = {} for digit_char in hand: digit_counts[digit_char] = digit_counts.get(digit_char, 0) + 1 counts = list(digit_counts.values()) counts.sort(reverse=True) return countsDesign extensible category evaluators
If we hard-coded a 7-branch
if/elifblock insidecompare_hands, adding an 8th category later would force us to edit the comparison function itself.Instead, we create a
CategoryEvaluatorbase class with a singlematches(hand, counts) -> boolmethod, and write one small subclass per category. Notice we pass bothhand(the raw string) andcounts(the sorted frequencies): current categories checkcounts, while a future category likeStraightorPalindromecan inspecthanddirectly without changingHandComparatoror any existing subclass!from typing import List class CategoryEvaluator: """Base interface for one hand category in our extensible rule list.""" name = "category" def matches(self, hand: str, counts: List[int]) -> bool: raise NotImplementedError class FiveOfAKind(CategoryEvaluator): name = "five of a kind" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [5] class FourOfAKind(CategoryEvaluator): name = "four of a kind" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [4, 1] class FullHouse(CategoryEvaluator): name = "full house" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [3, 2] class TwoPair(CategoryEvaluator): name = "two pair" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [2, 2, 1] class ThreeOfAKind(CategoryEvaluator): name = "three of a kind" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [3, 1, 1] class OnePair(CategoryEvaluator): name = "one pair" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [2, 1, 1, 1] class HighCard(CategoryEvaluator): name = "high card" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [1, 1, 1, 1, 1]Compare category strength first, then scan right to left
HandComparatoracceptsevaluatorsordered from strongest to weakest. For any hand, the first evaluator atindexthat matches receivesstrength = len(evaluators) - index(7forFiveOfAKinddown to1forHighCard).When two hands have equal
strength, we scan indices4, 3, 2, 1, 0on the original strings:index: 0 1 2 3 4 hand1: '9' '9' '1' '1' '2' (Two pair: [2, 2, 1]) hand2: '1' '1' '9' '9' '2' (Two pair: [2, 2, 1]) ^-- pos = 4: '2' == '2' (keep scanning left) ^------ pos = 3: '1' < '9' --> hand2 wins (return 2)!Even though both hands hold two
9s, two1s, and one2,hand2wins because its'9'sits at index3wherehand1has'1'.class HandComparator: """Compares two numeric hands using an ordered list of CategoryEvaluator objects.""" def __init__(self, evaluators: List[CategoryEvaluator]) -> None: self.evaluators = evaluators def category_strength(self, hand: str) -> int: """Return integer category rank (len(evaluators) for strongest down to 1 for weakest).""" counts = compute_multiplicities(hand) for index, evaluator in enumerate(self.evaluators): if evaluator.matches(hand, counts): return len(self.evaluators) - index raise ValueError(f"No category matched hand: {hand}") def compare(self, hand1: str, hand2: str) -> int: strength1 = self.category_strength(hand1) strength2 = self.category_strength(hand2) if strength1 > strength2: return 1 if strength2 > strength1: return 2 for pos in range(len(hand1) - 1, -1, -1): digit1 = int(hand1[pos]) digit2 = int(hand2[pos]) if digit1 > digit2: return 1 if digit2 > digit1: return 2 return 0Trace Examples 1 and 2 step by step
Trace 1 (Example 1 — different categories): hand1 = "88852" --> counts = [3, 1, 1] --> ThreeOfAKind (strength 3) hand2 = "44661" --> counts = [2, 2, 1] --> TwoPair (strength 4) strength2 (4) > strength1 (3) --> return 2 immediately (TwoPair outranks ThreeOfAKind). Trace 2 (Example 2 — same category, right-to-left tie-break): hand1 = "25774" --> counts = [2, 1, 1, 1] --> OnePair (strength 2) hand2 = "77254" --> counts = [2, 1, 1, 1] --> OnePair (strength 2) strength1 == strength2 == 2, so scan from pos = 4 down to 0: pos = 4: hand1[4] = 4 vs hand2[4] = 4 (equal, continue left) pos = 3: hand1[3] = 7 vs hand2[3] = 5 --> 7 > 5 --> return 1. (Sorting the hands first would have turned both into "77542" and falsely returned 0!)Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def compute_multiplicities(hand: str) -> List[int]: """Count how many times each digit appears, sorted largest first: '55588' -> [3, 2].""" # digit_counts: maps digit character -> frequency in hand, e.g. {'5': 3, '8': 2} digit_counts: Dict[str, int] = {} for digit_char in hand: digit_counts[digit_char] = digit_counts.get(digit_char, 0) + 1 # Sorting counts descending creates a canonical shape independent of which digits appeared. counts = list(digit_counts.values()) counts.sort(reverse=True) return counts class CategoryEvaluator: """Base interface for one hand category in our extensible rule list.""" name = "category" def matches(self, hand: str, counts: List[int]) -> bool: # Passing both the raw hand and sorted counts lets future subclasses check # digit values or positions (such as a straight) without changing HandComparator. raise NotImplementedError class FiveOfAKind(CategoryEvaluator): name = "five of a kind" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [5] class FourOfAKind(CategoryEvaluator): name = "four of a kind" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [4, 1] class FullHouse(CategoryEvaluator): name = "full house" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [3, 2] class TwoPair(CategoryEvaluator): name = "two pair" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [2, 2, 1] class ThreeOfAKind(CategoryEvaluator): name = "three of a kind" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [3, 1, 1] class OnePair(CategoryEvaluator): name = "one pair" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [2, 1, 1, 1] class HighCard(CategoryEvaluator): name = "high card" def matches(self, hand: str, counts: List[int]) -> bool: return counts == [1, 1, 1, 1, 1] class HandComparator: """Compares two numeric hands using an ordered list of CategoryEvaluator objects.""" def __init__(self, evaluators: List[CategoryEvaluator]) -> None: # evaluators: ordered strongest to weakest; earlier match = higher strength self.evaluators = evaluators def category_strength(self, hand: str) -> int: """Return integer category rank (len(evaluators) for strongest down to 1 for weakest).""" counts = compute_multiplicities(hand) for index, evaluator in enumerate(self.evaluators): if evaluator.matches(hand, counts): return len(self.evaluators) - index raise ValueError(f"No category matched hand: {hand}") def compare(self, hand1: str, hand2: str) -> int: # Phase 1: compare category strength first. strength1 = self.category_strength(hand1) strength2 = self.category_strength(hand2) if strength1 > strength2: return 1 if strength2 > strength1: return 2 # Phase 2: same category -> scan ORIGINAL positions from right (index 4) to left (index 0). # Never sort the hands: original card positions decide ties here. for pos in range(len(hand1) - 1, -1, -1): digit1 = int(hand1[pos]) digit2 = int(hand2[pos]) if digit1 > digit2: return 1 if digit2 > digit1: return 2 return 0 # EVALUATORS defines the game's custom hierarchy: note TwoPair ranks above ThreeOfAKind. EVALUATORS: List[CategoryEvaluator] = [ FiveOfAKind(), FourOfAKind(), FullHouse(), TwoPair(), ThreeOfAKind(), OnePair(), HighCard(), ] DEFAULT_COMPARATOR = HandComparator(EVALUATORS) def compare_hands(hand1: str, hand2: str) -> int: return DEFAULT_COMPARATOR.compare(hand1, hand2)✅ Submit now — all tests should pass.
Intuition & how it works
Think of judging two hands as a two-stage inspection line with plug-in rule cards. Instead of tangling all seven category checks inside one long if/elif function, we use the strategy pattern (an object-oriented design where each rule lives in its own small interchangeable class sharing a common method). We line up our category rule cards from strongest to weakest and find the first card each hand matches; only if both hands match the exact same rule card do we move to stage two and read the two untouched 5-digit strings backward from right to left.
A naive poker-style implementation trips over three traps here. First, standard poker puts three of a kind above two pair, whereas this game explicitly puts TwoPair above ThreeOfAKind. Second, sorting the cards or comparing pair values before singletons destroys the original card positions needed for the right-to-left tie-breaker ("12345" beats "54321" because index 4 has 5 > 1). Third, hard-coding categories inside compare_hands violates the open-closed principle (structuring code so new behaviors can be added by registering new classes rather than editing working comparison logic).
Each current category depends only on digit multiplicities (the repeat counts of distinct digits in the hand, sorted largest first, such as [3, 2] for "55588"). Passing both (hand, counts) into evaluator.matches(hand, counts) makes multiplicity rules one-liners while leaving the door wide open for digit-based or position-based rules later.
Walk through Examples 1 and 2:
1. "88852" vs "44661": "88852" has multiplicities [3, 1, 1] (ThreeOfAKind, index 4 -> strength 3), while "44661" has [2, 2, 1] (TwoPair, index 3 -> strength 4). Strength 4 > 3, so "44661" wins (2).
2. "25774" vs "77254": both have [2, 1, 1, 1] (OnePair, strength 2). Scanning right to left: at index 4, '4' == '4'; at index 3, '7' > '5', so "25774" wins (1).
Complexity
Let k be the hand length (5 here) and C be the number of category evaluators (7 here).
- Time:
O(k log k + C * k)per call — which isO(1)constant time fork = 5andC = 7. Counting digits in a dictionary takesO(k)steps, sorting at mostkcounts takesO(k log k)steps, checking up toCevaluators compares lists of length at mostk, and the right-to-left tie-break inspects at mostkcharacters. - Space:
O(k)(O(1)fork = 5) to hold the frequency dictionary and sorted multiplicity list for one hand at a time. TheEVALUATORSlist andDEFAULT_COMPARATORare instantiated once at module load and reused across calls.
Edge cases
- Five of a kind (
"11111"vs"99998"): unlike a 4-suit deck, five identical digits are legal and beat every four-of-a-kind regardless of digit values (1). - Custom
TwoPairvsThreeOfAKindorder ("11223"vs"99912"): returns1becauseTwoPairsits ahead ofThreeOfAKindinEVALUATORS. - Same digits in reversed order (
"12345"vs"54321"): both areHighCard, and index4(5vs1) gives1. - Equal pairs in different positions (
"99112"vs"11992"): standard poker would call this a tie (9s and1s with a2kicker), but right-to-left position comparison decides at index3(2). - First four right-to-left positions tied (
"91234"vs"81234"): the loop steps all the way down topos = 0(9vs8) and returns1. - Identical strings (
"44884"vs"44884"): equal category strength and equal digits at all 5 indices return0.
Common mistakes
- Ranking
ThreeOfAKindaboveTwoPairout of poker habit: fails immediately on"11223"vs"99912". - Sorting hands or grouping pairs before breaking ties: alters card indices and breaks right-to-left positional comparison.
- Scanning ties left to right (
0..4) instead of right to left (4..0): flips the winner on"12345"vs"54321". - Testing
3 in countsbeforecounts == [3, 2]: misclassifies every full house as three of a kind; comparing the full sorted listcounts == [3, 1, 1]avoids any ordering fragility between those two rules. - Passing only
countstoCategoryEvaluator.matches: works for multiplicity categories, but forces you to change the base interface and every subclass as soon as an interviewer asks for aStraightfollow-up.
Alternative approaches
- Precomputed sort-key tuple
(category_strength, hand[::-1]): because'1'through'9'are single ASCII characters whose character codes increase in numeric order, reversing the string (hand[::-1]) compares right-to-left positions naturally. Keepint(hand[pos])incompareif card tokens could ever widen to multi-character values like"10". - Data-driven
(name, target_counts)table: if every possible future rule were guaranteed to depend only on multiplicities, a list of tuples like[("five of a kind", [5]), ...]would avoid subclasses altogether; theCategoryEvaluatorclass hierarchy shines when rules have custom matching logic.
Follow-up questions
- How could you introduce a Straight category (five consecutive digits in any order) without modifying HandComparator? Because
CategoryEvaluator.matches(self, hand, counts)already receives bothhandandcounts, write one new subclass and insertStraight()intoEVALUATORSwherever it belongs in the ranking (aboveHighCard, since both havecounts == [1, 1, 1, 1, 1]and the first matching evaluator wins):
```python class Straight(CategoryEvaluator): name = "straight"
def matches(self, hand: str, counts: List[int]) -> bool:
if counts != [1, 1, 1, 1, 1]:
return False
digits = [int(ch) for ch in hand]
return max(digits) - min(digits) == 4
```
- How would you rank and sort a list of N hands efficiently instead of comparing pairs repeatedly? Add a
sort_key(hand)method onHandComparatorreturning(self.category_strength(hand), [int(ch) for ch in reversed(hand)]), then callhands.sort(key=comparator.sort_key, reverse=True). Computing each hand's key once doesO(N)evaluations plusO(N log N)cheap tuple comparisons, whereas wrappingcomparewithfunctools.cmp_to_keyre-evaluatescompute_multiplicitieson every comparison (O(N log N)evaluations). - What change would let individual hand categories customize their own tie-breaking logic? Move a
tiebreak_key(self, hand: str)method ontoCategoryEvaluatorwith the default implementation returning[int(ch) for ch in reversed(hand)]. ThenHandComparatorsimply compares(strength1, evaluator1.tiebreak_key(hand1))against(strength2, evaluator2.tiebreak_key(hand2)), allowing any single category to override its tie-breaker without touchingHandComparator.
Follow-up questions
- How could you introduce a Straight category (five consecutive digits in any order) without modifying HandComparator?
- How would you rank and sort a list of N hands efficiently instead of comparing pairs repeatedly?
- What change would let individual hand categories customize their own tie-breaking logic?
Similar questions
- Single-Pass Employee Spend Breakdowns
- Courier Trip Billing with Historical Rates
- Expense Policy Rule Evaluator
- Winning Draw Check for Incomplete Poker Hands
- Evaluating Complete and Incomplete Card Hands
- Active Drivers Over 24-Hour Window
More Rippling interview questions
- Logarithmic Median of Two Sorted Arrays Medium
- Multi-Hop Currency Conversion and Best Simple Route Easy
- User Article Vote History Tracker Easy Pro
- In-Memory Courier Wage Ledger with Cutoff Payouts Medium Pro
- Numeric Five-Card Hand Evaluator and Partial-Hand Completions Medium Pro
- Hourly Payroll Service for Delivery Couriers Medium Pro
- Pluggable Broadcast Logger and Inverted-Index Keyword Search Easy Pro
- Global News Aggregation Platform Medium Pro
- In-Memory Delivery Cost Tracker Medium Pro
- Explicit-Preference News Feed Aggregator Medium Pro