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:

  1. 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.

  2. 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, return 0.

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) == 5 and len(hand2) == 5.
  • Every character of hand1 and hand2 is a digit from '1' to '9' inclusive.

Step-by-step walkthrough

  1. Understand the custom ranking and tie-break rules

    We are given two 5-character strings (hand1 and hand2) made of digits '1' through '9', and we return 1 if hand1 wins, 2 if hand2 wins, or 0 if they tie.

    Read the game rules carefully, because three details intentionally differ from standard poker:

    1. Five of a kind exists: digits are not limited to 4 suits, so "11111" is valid and is the strongest category.
    2. 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. Notice Two pair outranks Three of a kind!
    3. 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.

  2. 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] vs counts == [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 counts
    
  3. Design extensible category evaluators

    If we hard-coded a 7-branch if/elif block inside compare_hands, adding an 8th category later would force us to edit the comparison function itself.

    Instead, we create a CategoryEvaluator base class with a single matches(hand, counts) -> bool method, and write one small subclass per category. Notice we pass both hand (the raw string) and counts (the sorted frequencies): current categories check counts, while a future category like Straight or Palindrome can inspect hand directly without changing HandComparator or 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]
    
  4. Compare category strength first, then scan right to left

    HandComparator accepts evaluators ordered from strongest to weakest. For any hand, the first evaluator at index that matches receives strength = len(evaluators) - index (7 for FiveOfAKind down to 1 for HighCard).

    When two hands have equal strength, we scan indices 4, 3, 2, 1, 0 on 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, two 1s, and one 2, hand2 wins because its '9' sits at index 3 where hand1 has '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 0
    
  5. Trace 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!)
    
  6. 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 is O(1) constant time for k = 5 and C = 7. Counting digits in a dictionary takes O(k) steps, sorting at most k counts takes O(k log k) steps, checking up to C evaluators compares lists of length at most k, and the right-to-left tie-break inspects at most k characters.
  • Space: O(k) (O(1) for k = 5) to hold the frequency dictionary and sorted multiplicity list for one hand at a time. The EVALUATORS list and DEFAULT_COMPARATOR are 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 TwoPair vs ThreeOfAKind order ("11223" vs "99912"): returns 1 because TwoPair sits ahead of ThreeOfAKind in EVALUATORS.
  • Same digits in reversed order ("12345" vs "54321"): both are HighCard, and index 4 (5 vs 1) gives 1.
  • Equal pairs in different positions ("99112" vs "11992"): standard poker would call this a tie (9s and 1s with a 2 kicker), but right-to-left position comparison decides at index 3 (2).
  • First four right-to-left positions tied ("91234" vs "81234"): the loop steps all the way down to pos = 0 (9 vs 8) and returns 1.
  • Identical strings ("44884" vs "44884"): equal category strength and equal digits at all 5 indices return 0.

Common mistakes

  • Ranking ThreeOfAKind above TwoPair out 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 counts before counts == [3, 2]: misclassifies every full house as three of a kind; comparing the full sorted list counts == [3, 1, 1] avoids any ordering fragility between those two rules.
  • Passing only counts to CategoryEvaluator.matches: works for multiplicity categories, but forces you to change the base interface and every subclass as soon as an interviewer asks for a Straight follow-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. Keep int(hand[pos]) in compare if 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; the CategoryEvaluator class 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 both hand and counts, write one new subclass and insert Straight() into EVALUATORS wherever it belongs in the ranking (above HighCard, since both have counts == [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 on HandComparator returning (self.category_strength(hand), [int(ch) for ch in reversed(hand)]), then call hands.sort(key=comparator.sort_key, reverse=True). Computing each hand's key once does O(N) evaluations plus O(N log N) cheap tuple comparisons, whereas wrapping compare with functools.cmp_to_key re-evaluates compute_multiplicities on 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 onto CategoryEvaluator with the default implementation returning [int(ch) for ch in reversed(hand)]. Then HandComparator simply compares (strength1, evaluator1.tiebreak_key(hand1)) against (strength2, evaluator2.tiebreak_key(hand2)), allowing any single category to override its tie-breaker without touching HandComparator.

Follow-up questions

Similar questions

More Rippling interview questions

All 106 Rippling questions →