Four-Card Hand Ranker with Extensible Type System
Data Structure DesignAuto-graded · 22 test casesLast updated
Tests object-oriented design skills by building a modular, open/closed hand classifier and comparator for a custom four-card game.
Four-Card Hand Ranker
You are building the core logic for a two-player card game called Dune Deck. Each player holds exactly 4 cards. Your job is to classify each hand and decide which player wins.
Card Values
Cards are labeled 1 through 9. 9 is the strongest and 1 is the weakest.
Hand Types
Every hand falls into exactly one category. Listed from strongest to weakest:
| Rank | Name | Description | Example |
|---|---|---|---|
| 1st | Four of a Kind | All four cards identical | 9999 |
| 2nd | Two Pair | Two distinct pairs | 2332 |
| 3rd | Three of a Kind | Exactly three cards identical, one different | 9998 |
| 4th | One Pair | Exactly one pair, two distinct others | 5233 |
| 5th | High Card | All four cards different | 2345 |
This ordering is intentional and non-standard. Two Pair outranks Three of a Kind in Dune Deck. Implement the order exactly as listed above.
Determining the Winner
- By type: the hand with the stronger type wins outright.
- By position (tiebreak): if both hands share the same type, compare cards right to left in dealt order (do not sort). Compare the last card of each hand; if they differ, the higher value wins. If equal, move one position left and repeat. If every position matches, the result is a TIE.
Your Task
Implement a function that accepts two hands and returns which player wins:
- Return
"HAND_1"if the first hand is stronger. - Return
"HAND_2"if the second hand is stronger. - Return
"TIE"if both hands are completely equal under the rules above.
Each hand may arrive as a 4-character string (e.g. "2332") or as a list of four values (e.g. ['2','3','3','2'] or [2,3,3,2]). Your solution must accept either form.
Design Requirement
The game will introduce additional hand types in future updates. Structure your solution so that a new hand type can be added by writing new code only — the classification loop, the comparator, and the evaluator function must require zero edits.
Constraints
- Each hand contains exactly 4 cards.
- Card labels are single digits in the range
1–9inclusive. - Input is either a plain string of four digit characters or a list of four single-character strings or integers.
- You may assume all inputs are valid and well-formed.
- Optimize for clarity and extensibility. With only 4 cards, raw performance is irrelevant.
Examples
Example 1
Input: evaluate('2332', '9998')
Output: 'HAND_1'
Example 2
Input: evaluate('9999', '8888')
Output: 'HAND_1'
Example 3
Input: evaluate('5233', '5332')
Output: 'HAND_1'
Example 4
Input: evaluate('1234', '4321')
Output: 'HAND_1'
Hints
Hint 1
Use a sorted list of frequency counts (e.g., [3, 1] for three-of-a-kind) as a fingerprint — each hand type maps to a unique fingerprint, and matching against it keeps classification fully self-contained per type class.
Hint 2
Give each hand-type class a numeric rank attribute and store all types in a single registry tuple. The classification loop just walks that tuple and returns the first match — adding a new type means appending to the tuple, nothing else.
Hint 3
For the right-to-left tiebreak, use reversed() on the normalized card tuples and zip them together. Never sort the cards for comparison; the dealt order is intentional and sorting would give wrong results for hands like '5233' vs '5332'.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has three clearly separable responsibilities: normalizing input, classifying a hand into a type, and comparing two classified hands. Keeping these in distinct, independently changeable units is what makes the design extensible.
1. Normalization
A single _normalize function converts any incoming format — string, list of strings, list of ints — into a plain tuple[int, ...]. Every downstream step works on that uniform representation, so the rest of the code never checks input format again.
2. Classification via the Open/Closed pattern
Each hand type lives in its own class that inherits from HandType. The class carries two things:
- A
rankinteger encoding the strength order from the problem statement. - A
matches(counts)classmethod that receives the sorted descending frequency list and returnsTrueorFalse.
The frequency list is a compact, format-independent fingerprint:
| Hand type | Sorted frequency counts |
|---|---|
| Four of a Kind | [4] |
| Two Pair | [2, 2] |
| Three of a Kind | [3, 1] |
| One Pair | [2, 1, 1] |
| High Card | [1, 1, 1, 1] |
The classifier walks a registry tuple HAND_TYPES and returns the first match. Adding a future type (say, a straight flush) means writing one new class and inserting it into HAND_TYPES — the classifier, comparator, and evaluate function are untouched. That satisfies the Open/Closed requirement.
3. Comparison
Once both hands are classified:
- Compare their
rankvalues. If different, the higher rank wins immediately. - If ranks are equal, walk the two card tuples right to left using
zip(reversed(cards1), reversed(cards2))and return on the first positional difference. - If every position matches, return
"TIE".
The tiebreak deliberately uses the raw dealt order rather than a sorted copy. Sorting would give the wrong answer for hands like "5233" vs "5332" — both are One Pair, but their dealt order differs and the last card determines the winner.
Why the non-standard type order is safe
The ordering Two Pair > Three of a Kind is encoded purely in the rank attribute of each class. Changing or reordering hand type strengths requires only updating those integer constants, not any comparison logic.
Complexity
With a fixed hand size of 4, all operations are O(1) in practice. The classification loop visits at most 5 types. There is no asymptotic concern here; readability and extensibility are the metrics that matter.
Reference solution
from collections import Counter
from typing import List, Tuple, Union
class HandType:
rank: int = 0
@classmethod
def matches(cls, counts: List[int]) -> bool:
raise NotImplementedError
class FourOfAKind(HandType):
rank = 5
@classmethod
def matches(cls, counts: List[int]) -> bool:
return counts == [4]
class TwoPair(HandType):
rank = 4
@classmethod
def matches(cls, counts: List[int]) -> bool:
return counts == [2, 2]
class ThreeOfAKind(HandType):
rank = 3
@classmethod
def matches(cls, counts: List[int]) -> bool:
return counts == [3, 1]
class OnePair(HandType):
rank = 2
@classmethod
def matches(cls, counts: List[int]) -> bool:
return counts == [2, 1, 1]
class HighCard(HandType):
rank = 1
@classmethod
def matches(cls, counts: List[int]) -> bool:
return counts == [1, 1, 1, 1]
HAND_TYPES = (FourOfAKind, TwoPair, ThreeOfAKind, OnePair, HighCard)
def _normalize(hand: Union[str, List]) -> Tuple[int, ...]:
return tuple(int(card) for card in hand)
def _classify(cards: Tuple[int, ...]) -> HandType:
counts = sorted(Counter(cards).values(), reverse=True)
for hand_type in HAND_TYPES:
if hand_type.matches(counts):
return hand_type
raise ValueError(f"No registered hand type matched counts {counts}")
def evaluate(hand1: Union[str, List], hand2: Union[str, List]) -> str:
cards1 = _normalize(hand1)
cards2 = _normalize(hand2)
type1 = _classify(cards1)
type2 = _classify(cards2)
if type1.rank != type2.rank:
return "HAND_1" if type1.rank > type2.rank else "HAND_2"
for c1, c2 in zip(reversed(cards1), reversed(cards2)):
if c1 != c2:
return "HAND_1" if c1 > c2 else "HAND_2"
return "TIE"