KatInterview

Digit Hand Showdown

Data Structure DesignAuto-graded · 23 test cases
MediumAuto-gradedData Structure Designobject-oriented-designpattern-matchingextensibility

Last 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:

  1. Five of a kind — all five digits are the same
  2. Four of a kind — four digits match
  3. Full house — three of one digit and two of another
  4. Two pair — two different pairs plus one unmatched digit
  5. Three of a kind — three matching digits
  6. One pair — exactly two matching digits
  7. 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.