Forced Winner in Complete and Incomplete Card Hands
Arrays & HashingAuto-graded · 21 test casesLast updated
Rank five-card hands with a tuple key, then decide whether an outcome is forced across all ways to fill in missing cards.
Two players are dealt cards in a simplified poker-style game. Each hand is given as a list of card strings. A card is written as rank followed by suit, for example "10H" or "AS".
- Rank is one of
2,3,4,5,6,7,8,9,10,J,Q,K,A. Ranks increase in that order, and the ace is always the highest. - Suit is one of
S,H,D,C. Suits never affect strength.
Write a function that takes the first player's cards and the second player's cards and reports who wins.
Ranking a complete hand
A complete hand has exactly 5 cards. Categories, from strongest to weakest:
- Four of a kind
- Full house
- Three of a kind
- Two pair
- One pair
- High card
There are no straights or flushes in this game. A hand such as 2, 3, 4, 5, 6 is just a high-card hand.
If both hands are in the same category, compare these ranks in order. The first difference decides the winner:
| Category | Comparison order |
|---|---|
| Four of a kind | rank of the four matching cards, then the remaining card |
| Full house | rank of the three matching cards, then rank of the pair |
| Three of a kind | rank of the three matching cards, then the other two cards from highest to lowest |
| Two pair | higher pair, then lower pair, then the remaining card |
| One pair | rank of the pair, then the other three cards from highest to lowest |
| High card | all five ranks from highest to lowest |
If every comparison is equal, the hands are tied.
Incomplete hands
Sometimes a hand has fewer than 5 cards because some have not arrived yet. In that case, consider every valid way to fill in the missing cards:
- Each final hand has exactly 5 cards.
- The missing cards come from the standard 52-card deck, excluding the cards already present in either hand.
- No card may appear twice among the final 10 cards, including across the two hands.
Return:
"user1"if the first player wins in every valid completion,"user2"if the second player wins in every valid completion,"tie"if every valid completion is a tie,"unknown"in all other cases.
When both hands already have 5 cards, there is exactly one completion, so the result is simply "user1", "user2", or "tie".
Constraints
- Each hand has between 0 and 5 cards.
- All cards given across both hands are distinct and valid.
- Rank
10is written with two characters, for example"10D". - The return value is exactly one of
"user1","user2","tie","unknown". - Suits are ignored when comparing strength.
Examples
Example 1
Input: judge_card_duel(['AS', 'AH', 'AD', 'AC', '2S'], ['KS', 'KH', 'KD', 'KC', '3S'])
Output: 'user1'
Example 2
Input: judge_card_duel(['2S', '2H', '2D', '3S', '3H'], ['AS', 'AH', 'AD', 'KS', 'KH'])
Output: 'user2'
Example 3
Input: judge_card_duel(['AS', 'KH', 'QD', 'JC', '9S'], ['AD', 'KC', 'QH', 'JS', '9D'])
Output: 'tie'
Example 4
Input: judge_card_duel(['AS', 'AH', 'AD'], ['KS', 'KH'])
Output: 'unknown'
Hints
Hint 1
Turn each complete hand into a tuple such as (category, tiebreak1, tiebreak2, ...) so that ordinary tuple comparison matches the rules.
Hint 2
Count how often each rank appears and sort the (count, rank) pairs in descending order. The shape of the largest groups gives the category. Remember to strip only the last character of a card so that 10 is parsed correctly.
Hint 3
For incomplete hands, enumerate completions: choose the first player's missing cards from the unused deck, then the second player's from what is left. Stop with unknown as soon as two different outcomes have appeared.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Scoring a complete hand. Convert each 5-card hand into a tuple (category, tiebreak...) whose entries follow the tie-break order in the statement. Python compares tuples lexicographically, so a single > comparison between two tuples gives the winner, and equal tuples mean a tie.
Build the tuple by counting ranks, using only the part of each card before the final suit letter (so "10H" becomes rank 10). Sort the (count, rank) groups in descending order. Then:
- Largest group of 4:
(5, quad, kicker). - Group of 3 followed by group of 2:
(4, triple, pair). - Group of 3 only:
(3, triple, higher kicker, lower kicker). - Two groups of 2:
(2, high pair, low pair, kicker). - One group of 2:
(1, pair, three kickers descending). - Otherwise:
(0, five ranks descending).
Incomplete hands. Remove all known cards from the 52-card deck. For the first player, iterate over every combination of the needed number of missing cards. For each choice, remove those cards from the pool and iterate over every combination for the second player. Score both final hands and record the outcome (first wins, second wins, or tie). As soon as two different outcomes have been recorded, the answer must be "unknown", so return immediately. If enumeration finishes with a single outcome, that outcome is forced and is returned.
Why it is correct
- Lexicographic comparison first checks the category, so a stronger category always wins, and then walks the tie-break ranks in exactly the order the rules specify. Equal tuples occur exactly when the hands are equal in strength.
- Dropping the suit makes the scoring ignore suits, as required.
- Choosing the first player's cards from the unused deck and the second player's from the remainder generates every valid pair of completions exactly once and never reuses a card.
- A result is forced only if all completions agree, so stopping once two outcomes are seen cannot miss a forced answer.
- If both hands are complete, the code takes a direct path with one comparison. The enumeration would also give the same answer with a single empty completion.
Complexity
- Complete hands: O(1) time and space, since there are always 5 cards.
- Incomplete hands: in the worst case about C(n, need1) · C(n − need1, need2) completions are checked, each scored in O(1), with n at most 52 minus the known cards. Undecided positions usually exit after a few iterations. The slowest cases are forced results with many missing cards.
- Space: O(52) for the deck plus a constant-size set of outcomes.
Reference solution
from collections import Counter
from itertools import combinations
from typing import List
RANK_VALUE = {str(i): i for i in range(2, 11)}
RANK_VALUE.update({"J": 11, "Q": 12, "K": 13, "A": 14})
SUIT_LETTERS = "SHDC"
FULL_DECK = [
f"{rank}{suit}"
for rank in list(map(str, range(2, 11))) + ["J", "Q", "K", "A"]
for suit in SUIT_LETTERS
]
def _strength(hand):
counts = Counter(RANK_VALUE[card[:-1]] for card in hand)
groups = sorted(((c, r) for r, c in counts.items()), reverse=True)
ranks_desc = sorted(counts.elements(), reverse=True)
if groups[0][0] == 4:
quad = groups[0][1]
return (5, quad, max(r for r in counts if r != quad))
if groups[0][0] == 3 and groups[1][0] == 2:
return (4, groups[0][1], groups[1][1])
if groups[0][0] == 3:
triple = groups[0][1]
return (3, triple, *sorted((r for r in counts.elements() if r != triple), reverse=True))
pairs = sorted((r for r, c in counts.items() if c == 2), reverse=True)
if len(pairs) == 2:
kicker = next(r for r, c in counts.items() if c == 1)
return (2, pairs[0], pairs[1], kicker)
if len(pairs) == 1:
pair = pairs[0]
return (1, pair, *sorted((r for r in counts.elements() if r != pair), reverse=True))
return (0, *ranks_desc)
def judge_card_duel(first_hand: List[str], second_hand: List[str]) -> str:
if len(first_hand) == 5 and len(second_hand) == 5:
a, b = _strength(first_hand), _strength(second_hand)
return "user1" if a > b else "user2" if b > a else "tie"
used = set(first_hand) | set(second_hand)
available = [card for card in FULL_DECK if card not in used]
need1 = 5 - len(first_hand)
need2 = 5 - len(second_hand)
outcomes = set()
for extra1 in combinations(available, need1):
taken = set(extra1)
s1 = _strength(first_hand + list(extra1))
rest = [card for card in available if card not in taken]
for extra2 in combinations(rest, need2):
s2 = _strength(second_hand + list(extra2))
outcomes.add(1 if s1 > s2 else 2 if s2 > s1 else 0)
if len(outcomes) > 1:
return "unknown"
if outcomes == {1}:
return "user1"
if outcomes == {2}:
return "user2"
if outcomes == {0}:
return "tie"
return "unknown"