Design a Five-Card Hand Evaluator with Partial Hand Completion
Data Structure DesignModel answerLast updated
Model poker-style five-card hands with an abstract type hierarchy, compare two hands by strength and tie-break, then find the strongest and weakest completions of a partial hand.
Five-Card Hand Evaluator
A card game is played with hands of exactly five cards. Every hand belongs to exactly one of seven categories, ranked from strongest to weakest:
| Rank | Name | Description |
|---|---|---|
| 1 | Five of a kind | All five cards share the same label |
| 2 | Four of a kind | Exactly four cards share a label |
| 3 | Full house | Three cards share one label, the remaining two share another |
| 4 | Three of a kind | Three cards share a label; the other two are distinct from it and each other |
| 5 | Two pair | Two cards share one label, two others share a second label, the fifth differs |
| 6 | One pair | Exactly two cards share a label; the other three are all different |
| 7 | High card | All five labels are distinct |
There is no upper limit on duplicates per label, so five of a kind is achievable. A stronger category always beats a weaker one regardless of labels.
Constraints
- A complete hand contains exactly five cards.
- Card labels are single characters drawn from a defined, ordered alphabet (clarify the exact set and ordering before coding).
- When two hands share the same category, resolve the tie by comparing cards left to right in dealt order, using the label ranking.
- A hand's category must be determined once at construction time, not recomputed on every comparison.
Part 1 — Object model and comparison
Design an abstract class HandType and a class Hand. Before writing any code, explain:
- What
HandTypeabstracts and how each of the seven categories extends it. - What data
Handstores and how it determines its type at construction. - How
evaluate(hand_a, hand_b)decides which hand is stronger.
Then implement the classes and the function. State the time complexity of constructing a hand and of a single comparison. Address input validation: what happens when a hand has the wrong number of cards or contains an unknown label?
Part 2 — Best and worst completions of a partial hand
You are given between zero and four known cards; the rest are unknown. Return the strongest possible complete hand (best_hand) and the weakest possible complete hand (worst_hand) that both include all of the known cards.
Example: if the two known cards are both 9, the strongest completion is 99999 and the weakest is 99321 (assuming 1 is the lowest-ranked label).
A brute-force approach is acceptable. Implement it using the classes from Part 1, and provide a step-by-step time-complexity breakdown. Then discuss whether a direct construction could replace enumeration, and what that approach would need to guarantee.
Clarify before coding:
- Does the position of each known card in the final hand matter, or is a hand an unordered multiset?
- What should the function return if zero cards are known? If more than five are provided?
- When multiple completions tie for best or worst, which one is returned?
Hints
Hint 1
For HandType, the only thing that varies across the seven categories is the matching rule and the rank weight — everything else is shared behavior. A frequency map (label → count) over the five cards gives you all the information you need to classify any hand in O(1) for a fixed hand size.
Hint 2
Comparison happens in two stages: first compare the integer weights of the two HandType objects; only if those are equal do you fall through to a left-to-right card-by-card comparison using label rank. Make sure the tie-break order (dealt order vs. group size) is pinned down before you write the comparator.
Hint 3
For Part 2, the number of possible labels is a small constant L (at most 13 in a standard deck). You are choosing at most 5 cards from L labels with repetition allowed, so the search space is at most L^5, which is bounded and polynomial. Enumerate all valid completions, score each with your Part 1 hand, and track the running best and worst using your comparator.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Clarifications to lock in first
Before writing a line of code, confirm:
- Label set and ordering — e.g.,
23456789TJQKAlow to high, or a custom set including1. The ranking table must be explicit. - Tie-break order — dealt position left to right is the most common rule and the one used here. An alternative (compare the three-of-a-kind label before the pair in a full house) would change the comparator.
- Return value of
evaluate— a negative/zero/positive integer is more composable than returning one of the two hand objects. - Error handling — raise a
ValueErrorfor wrong card count or unknown labels.
Part 1 — Design explanation
HandType (abstract base)
Each category has two fixed pieces of data: a human-readable name and an integer weight (1 = strongest, 7 = weakest). The only thing that varies is the classification predicate — a method matches(counts: dict[str, int]) -> bool that receives the frequency map of a hand's cards and returns whether this type fits. Concrete subclasses override only that method. Ordering between two types reduces to comparing their weights.
Hand
Stores the five cards as an ordered list (preserving dealt position for tie-breaking) and a computed hand_type. At construction:
- Validate length and labels — O(1) for a fixed hand size.
- Build a frequency map — O(1).
- Check each
HandTypein descending strength order and assign the first match — O(1) since there are exactly seven types.
Total construction cost: O(1) for a fixed hand size of 5. If you allow variable-length hands it becomes O(n).
evaluate(hand_a, hand_b)
- Compare
hand_a.hand_type.weightvshand_b.hand_type.weight. Return the difference if non-zero. - Otherwise iterate the five card positions left to right, returning the first non-zero difference in label rank.
Cost: O(1) — at most seven type comparisons and five card comparisons.
Part 1 — Implementation
from abc import ABC, abstractmethod
from collections import Counter
from typing import Optional
# Define the label ordering. Adjust this list to match the actual spec.
LABEL_RANK: dict[str, int] = {
label: rank for rank, label in enumerate("23456789TJQKA", start=2)
}
class HandType(ABC):
def __init__(self, name: str, weight: int) -> None:
self.name = name
self.weight = weight # 1 = strongest, 7 = weakest
@abstractmethod
def matches(self, counts: dict[str, int]) -> bool:
...
def __repr__(self) -> str:
return self.name
class FiveOfAKind(HandType):
def __init__(self): super().__init__("Five of a Kind", 1)
def matches(self, counts): return max(counts.values()) == 5
class FourOfAKind(HandType):
def __init__(self): super().__init__("Four of a Kind", 2)
def matches(self, counts): return max(counts.values()) == 4
class FullHouse(HandType):
def __init__(self): super().__init__("Full House", 3)
def matches(self, counts): return sorted(counts.values()) == [2, 3]
class ThreeOfAKind(HandType):
def __init__(self): super().__init__("Three of a Kind", 4)
def matches(self, counts): return max(counts.values()) == 3 and len(counts) == 3
class TwoPair(HandType):
def __init__(self): super().__init__("Two Pair", 5)
def matches(self, counts): return sorted(counts.values()) == [1, 2, 2]
class OnePair(HandType):
def __init__(self): super().__init__("One Pair", 6)
def matches(self, counts): return max(counts.values()) == 2 and len(counts) == 4
class HighCard(HandType):
def __init__(self): super().__init__("High Card", 7)
def matches(self, counts): return len(counts) == 5
# Ordered strongest to weakest — iteration order matters for classification.
ALL_TYPES: list[HandType] = [
FiveOfAKind(), FourOfAKind(), FullHouse(),
ThreeOfAKind(), TwoPair(), OnePair(), HighCard(),
]
class Hand:
def __init__(self, cards: list[str]) -> None:
if len(cards) != 5:
raise ValueError(f"A hand requires exactly 5 cards, got {len(cards)}.")
for c in cards:
if c not in LABEL_RANK:
raise ValueError(f"Unknown label: '{c}'.")
self.cards = cards
counts = dict(Counter(cards))
self.hand_type: HandType = next(t for t in ALL_TYPES if t.matches(counts))
def __repr__(self) -> str:
return f"{''.join(self.cards)} ({self.hand_type})"
def evaluate(hand_a: Hand, hand_b: Hand) -> int:
"""Return negative if hand_a is stronger, positive if hand_b is stronger, 0 if equal."""
type_diff = hand_a.hand_type.weight - hand_b.hand_type.weight
if type_diff != 0:
return type_diff # higher weight = weaker hand, so lower weight wins (negative = a wins)
for ca, cb in zip(hand_a.cards, hand_b.cards):
rank_diff = LABEL_RANK[cb] - LABEL_RANK[ca] # higher rank wins
if rank_diff != 0:
return rank_diff
return 0
Common mistakes:
- Checking
FullHousebeforeThreeOfAKindis fine becauseFullHouse.matcheschecks for exactly two distinct labels; failing to be precise here produces misclassifications at the boundary. - Using
max(counts.values()) == 2alone doesn't distinguish one pair from two pair — you also need the count of distinct labels.
Part 2 — Best and worst completions
Brute-force strategy: generate every possible completion of the missing slots by iterating over all combinations with repetition from the label set, construct a Hand for each, and track the running best and worst using evaluate.
from itertools import product
def best_and_worst_completions(
known: list[str],
) -> tuple[Hand, Hand]:
if len(known) > 5:
raise ValueError("Cannot have more than 5 known cards.")
missing = 5 - len(known)
labels = list(LABEL_RANK.keys())
best: Optional[Hand] = None
worst: Optional[Hand] = None
for fill in product(labels, repeat=missing):
candidate = Hand(known + list(fill))
if best is None or evaluate(candidate, best) < 0:
best = candidate
if worst is None or evaluate(candidate, worst) > 0:
worst = candidate
return best, worst # type: ignore[return-value] # always set after ≥1 iteration
Time complexity breakdown:
| Factor | Value | Reason |
|---|---|---|
| Label set size | L | Fixed alphabet, e.g. L = 13 |
| Missing cards | k = 5 − (known cards) | At most 5 |
| Completions to check | L^k | At most 13^5 = 371,293 |
| Cost per completion | O(1) | Hand construction + one comparison, both O(1) for fixed size |
| Total | O(L^k) | Polynomial and bounded |
Because both hand size and label set are small constants, this is effectively O(1) in practice — a few hundred thousand iterations at most.
Could you construct best/worst directly? Yes, but it requires a proof for each of the seven types. For best_hand, greedily extend the most-frequent known label. For worst_hand, use the lowest-ranked distinct labels to avoid forming pairs. The brute-force approach is easier to verify correct and the runtime difference is negligible given the tiny search space.
Tie-break dependency: if multiple completions tie for best, product iteration order determines which is returned. Document this or add a secondary sort key if determinism matters.