Identify Missing Straight Rank
Easy · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
A standard 5-card poker straight consists of five consecutive card ranks chosen from A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K. Suppose four distinct cards from a valid 5-card straight are dealt to you in arbitrary order, leaving a single rank absent.
Implement find_missing_rank(ranks: List[str]) -> str to identify and return that omitted card rank.
Single-character symbol mapping used for both input and output:
'0'denotes Ace (A).'2'through'9'denote pip ranks2through9.'T'denotes10.'J','Q', and'K'denote Jack, Queen, and King.
Straight formation and tie-breaking rules:
- Ace (
'0') may sit at the bottom of the wheel straightA-2-3-4-5(acting as value1) or at the top of the broadway straight10-J-Q-K-A(acting as value14above King). Straights never wrap past both ends (for instance,Q-K-A-2-3is not legal). - Whenever the four supplied cards already form four consecutive ranks and could complete a valid 5-card straight on either end (such as
7-8-9-10, which fits both6-7-8-9-10and7-8-9-10-J, or2-3-4-5, which fits bothA-2-3-4-5and2-3-4-5-6), return the missing card belonging to the lower-ranked straight.
Examples
Example 1
Input:
ranks = ["7", "8", "9", "T"]
Output:
"6"
Walk-through: "T" stands for 10, so the four held cards 7, 8, 9, 10 are already consecutive and fit 6-7-8-9-10 as well as 7-8-9-10-J. Following the lower-straight tie-breaker selects 6-7-8-9-10 and returns "6".
Example 2
Input:
ranks = ["5", "0", "4", "2"]
Output:
"3"
Walk-through: Regardless of input order, "0" serves as a low Ace alongside 2, 4, and 5 in A-2-3-4-5, so the omitted interior card is "3".
Constraints
len(ranks) == 4- Every entry in
ranksis a distinct single-character string from{'0', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K'}. - The four entries are guaranteed to belong to at least one legal 5-card straight, and
ranksmay be unsorted.
Step-by-step walkthrough
Understand the encoding and the two tricky cases
We receive 4 distinct single-character symbols drawn from a 5-card poker straight with 1 rank omitted, and we must return that omitted symbol using the exact same single-character code:
'0'= Ace (A)'2'through'9'= 2 through 9'T'= 10'J','Q','K'= Jack, Queen, King
Two subtleties defeat a naive "sort the characters and find the gap" approach:
- Dual-role Ace without wrap-around: Ace acts as
1inA-2-3-4-5or as14in10-J-Q-K-A, never bridging across both ends likeQ-K-A-2-3. - Four already-consecutive cards have no interior gap: In Example 1 (
['7', '8', '9', 'T']), the missing card sits on an outer end, so both6-7-8-9-10(missing'6') and7-8-9-10-J(missing'J') fit. By rule, whenever two straights fit, we pick the lower-ranked straight. Likewise,['2', '3', '4', '5']completes downward toA-2-3-4-5('0'), and['T', 'J', 'Q', 'K']completes downward to9-T-J-Q-K('9').
Place every card code onto a numeric 1..14 scale
Lexicographic string sorting fails because ASCII places
'0'ahead of'2'and orders face symbols alphabetically ('J' < 'K' < 'Q' < 'T'). Instead, map every rank onto a1..14integer scale with Ace ('0') occupying both ends:Value: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Code: '0' '2' '3' '4' '5' '6' '7' '8' '9' 'T' 'J' 'Q' 'K' '0' (A) (10) (A)Two small dictionaries handle all conversions: -
RANK_VALUEmaps each symbol to its default numeric rank (2..14, mapping'0' -> 14), paired withcard_value(rank, ace_is_low)which overrides'0'to1only when testingA-2-3-4-5. -VALUE_RANKconverts any integer in1..14back to its symbol (mapping both1and14to'0').# RANK_VALUE: maps each single-character card code to its numeric rank (2..14), # treating Ace ('0') as 14 (high above King) by default. RANK_VALUE: Dict[str, int] = { "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11, "Q": 12, "K": 13, "0": 14, } # VALUE_RANK: maps numeric values 1..14 back to single-character card codes. # Both 1 (Ace-low) and 14 (Ace-high) decode back to '0'. VALUE_RANK: Dict[int, str] = { 1: "0", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "T", 11: "J", 12: "Q", 13: "K", 14: "0", } def card_value(rank: str, ace_is_low: bool) -> int: """Convert an encoded rank character to an integer, using 1 for Ace only in A-2-3-4-5.""" if rank == "0" and ace_is_low: return 1 return RANK_VALUE[rank]Key idea: check the 10 legal 5-card straights from lowest to highest
Every legal 5-card straight spans 5 consecutive integers
[low, low + 1, low + 2, low + 3, low + 4]on our1..14scale, solowtakes only 10 possible values (1through10):low = 1: [1, 2, 3, 4, 5] -> A-2-3-4-5 (ace_is_low = True) low = 2: [2, 3, 4, 5, 6] -> 2-3-4-5-6 (ace_is_low = False) ... low = 9: [9, 10, 11, 12, 13] -> 9-T-J-Q-K (ace_is_low = False) low = 10: [10, 11, 12, 13, 14] -> T-J-Q-K-A (ace_is_low = False)Because only 10 straights exist in the whole deck, we can avoid error-prone gap branching altogether by testing
low = 1, 2, ..., 10in ascending order:- Map the 4 distinct input symbols into a set
held_values(settingace_is_low = (low == 1)). Since all 4 symbols are distinct,held_valuesalways holds 4 distinct integers. - Collect every integer in
[low .. low + 4]absent fromheld_values. - Whenever exactly 1 integer is absent from
[low .. low + 4], the remaining 4 slots of that straight must all be inheld_values—meaning all 4 held cards lie inside this straight, and the single absent value is our answer!
Scanning
lowupward from1resolves every tie-breaker and boundary automatically: - For['7', '8', '9', 'T'],low = 6(6..10) runs beforelow = 7(7..11), returning'6'. - For['0', '2', '3', '4'], nothing sits below1, solow = 1(1..5) matches and returns'5'. - For['J', 'Q', 'K', '0'], nothing sits above14, solow = 10(10..14) matches and returns'T'.- Map the 4 distinct input symbols into a set
Code the straight search
def find_missing_rank(ranks: List[str]) -> str: # Every valid 5-card straight occupies [low, low + 1, low + 2, low + 3, low + 4] # for some starting value `low` in 1..10 (from A-2-3-4-5 up to T-J-Q-K-A). # Checking `low` from 1 upward ensures 4 consecutive cards (like 7-8-9-T) match # the lower straight first (6-7-8-9-T -> missing '6'), matching Example 1. for low in range(1, 11): ace_is_low = (low == 1) # Phase 1: Convert the 4 held cards into numeric values for this candidate straight. held_values: Set[int] = set() for rank in ranks: held_values.add(card_value(rank, ace_is_low)) # Phase 2: Collect which of the 5 straight slots [low .. low + 4] are missing. missing_values: List[int] = [] for value in range(low, low + 5): if value not in held_values: missing_values.append(value) # Because the 4 input cards are distinct, missing_values has length 1 if and only if # all 4 held cards lie inside [low .. low + 4], leaving the single missing rank. if len(missing_values) == 1: return VALUE_RANK[missing_values[0]] raise ValueError("Input ranks do not belong to any valid 5-card straight")Trace the examples and Ace-high boundary
Case 1: ranks = ['7', '8', '9', 'T'] (Example 1) low = 1..5: at least 2 slots in [low .. low + 4] are missing low = 6 (window 6..10): held = {7, 8, 9, 10} -> missing [6] (1 missing!) -> return '6' Case 2: ranks = ['5', '0', '4', '2'] (Example 2) low = 1 (window 1..5): ace_is_low = True, so '0' -> 1 held = {1, 2, 4, 5} -> missing [3] (1 missing!) -> return '3' Case 3: ranks = ['J', 'Q', 'K', '0'] (Ace-high straight) low = 1 (window 1..5): held = {1, 11, 12, 13} -> missing [2, 3, 4, 5] low = 2..9: held = {11, 12, 13, 14} -> at least 2 slots missing each time low = 10 (window 10..14): held = {11, 12, 13, 14} -> missing [10] (1 missing!) -> return 'T'Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # RANK_VALUE: maps each single-character card code to its numeric rank (2..14), # treating Ace ('0') as 14 (high above King) by default. RANK_VALUE: Dict[str, int] = { "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "T": 10, "J": 11, "Q": 12, "K": 13, "0": 14, } # VALUE_RANK: maps numeric values 1..14 back to single-character card codes. # Both 1 (Ace-low) and 14 (Ace-high) decode back to '0'. VALUE_RANK: Dict[int, str] = { 1: "0", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "T", 11: "J", 12: "Q", 13: "K", 14: "0", } def card_value(rank: str, ace_is_low: bool) -> int: """Convert an encoded rank character to an integer, using 1 for Ace only in A-2-3-4-5.""" if rank == "0" and ace_is_low: return 1 return RANK_VALUE[rank] def find_missing_rank(ranks: List[str]) -> str: # Every valid 5-card straight occupies [low, low + 1, low + 2, low + 3, low + 4] # for some starting value `low` in 1..10 (from A-2-3-4-5 up to T-J-Q-K-A). # Checking `low` from 1 upward ensures 4 consecutive cards (like 7-8-9-T) match # the lower straight first (6-7-8-9-T -> missing '6'), matching Example 1. for low in range(1, 11): ace_is_low = (low == 1) # Phase 1: Convert the 4 held cards into numeric values for this candidate straight. held_values: Set[int] = set() for rank in ranks: held_values.add(card_value(rank, ace_is_low)) # Phase 2: Collect which of the 5 straight slots [low .. low + 4] are missing. missing_values: List[int] = [] for value in range(low, low + 5): if value not in held_values: missing_values.append(value) # Because the 4 input cards are distinct, missing_values has length 1 if and only if # all 4 held cards lie inside [low .. low + 4], leaving the single missing rank. if len(missing_values) == 1: return VALUE_RANK[missing_values[0]] raise ValueError("Input ranks do not belong to any valid 5-card straight")✅ Submit now — all tests should pass.
Intuition & how it works
Imagine a 14-notch number line marked 1 through 14, with Ace ('0') appearing at notch 1 on the left and at notch 14 on the right, while '2'–'9', 'T', 'J', 'Q', and 'K' occupy notches 2 through 13. Every valid 5-card poker straight corresponds to a fixed-size window—a contiguous 5-notch frame [low .. low + 4]—positioned along that line (1..5 for A-2-3-4-5, 2..6 for 2-3-4-5-6, up to 10..14 for T-J-Q-K-A).
Sorting the 4 input characters directly and looking for a gap of 2 breaks in three ways: ASCII character order scrambles poker ranks ('0' < '2' and 'K' < 'Q' < 'T'), Ace changes numeric position between 1 and 14, and four consecutive cards like ['7', '8', '9', 'T'] contain no internal gap at all. Because only 10 legal 5-card straights exist in the entire deck, stepping low from 1 through 10 in ascending order and returning the lone empty notch of the first matching 5-notch frame handles every edge case cleanly.
Walk through our two examples:
- For
['5', '0', '4', '2'](Example 2), atlow = 1(frame1..5) we map'0'to1, formingheld_values = {1, 2, 4, 5}. Notch3is the sole empty slot in1..5, so we returnVALUE_RANK[3] = '3'. - For
['7', '8', '9', 'T'](Example 1), frames1..5through5..9each miss at least two notches. Atlow = 6(frame6..10),held_values = {7, 8, 9, 10}misses only6, so we immediately return'6'—satisfying the lower-straight tie-breaker automatically.
Complexity
- Time:
O(1). Both the deck size and hand size are fixed constants: the loop tests at most10candidate frames, and each iteration builds a4-item set and runs5O(1)set lookups (well under 100 primitive operations in the worst case). - Space:
O(1).RANK_VALUE(13keys) andVALUE_RANK(14keys) have constant size, and each iteration allocates at most a4-element set and a5-element list.
(Generalized to a straight of length K across an R-rank deck, checking R - K + 2 windows of width K runs in O(R * K) time and O(K) space.)
Edge cases
- Wheel straight missing its top card (
['0', '2', '3', '4']): Nothing exists below1, solow = 1(1..5) is the unique match and returns'5'. - Broadway straight (
['J', 'Q', 'K', '0']or['T', 'Q', 'K', '0']): Forlow >= 2,'0'maps to14, matchinglow = 10(10..14) and returning'T'or'J'. - Missing card is Ace (
['2', '3', '4', '5']): Frame1..5is tested before2..6, returning'0'. - Four consecutive high cards (
['T', 'J', 'Q', 'K']): Frame9..13is tested before10..14, returning'9'rather than'0'. - Missing
10(['7', '8', '9', 'J']):VALUE_RANK[10]returns'T', not'10'. - Arbitrary input order (
['5', '0', '4', '2']): Collecting mapped ranks into asetmakes input ordering irrelevant. - Wrap-around combinations (
K-A-2-3): Rejected automatically because Ace maps to either1(low == 1) or14(low >= 2), never both at once.
Common mistakes
- Sorting character strings directly: ASCII ordering puts
'0'first and sorts'J' < 'K' < 'Q' < 'T', breaking face-card comparisons. - Looking only for an interior difference of
2: Misses every hand where the 4 dealt cards are already consecutive (such as['7', '8', '9', 'T']in Example 1 or['0', '2', '3', '4']). - Treating Ace as fixed at
1or fixed at14: Fails eitherT-J-Q-K-AorA-2-3-4-5. - Completing four consecutive cards upward (
max + 1) instead of downward (min - 1): Returns'J'instead of'6'on Example 1. - Returning
'A'or'10'instead of'0'or'T': Violates the single-character symbol specification.
Alternative approaches
- Sort mapped values and branch on
max - min: Map'0'to1when all remaining cards are<= 5(else14), then sort[v0, v1, v2, v3]. Whenv3 - v0 == 4, scanv0 .. v3for the missing interior number; whenv3 - v0 == 3, return5ifv0 == 1, otherwisev0 - 1. It achieves the sameO(1)bound, though the 10-window scan avoids those manual boundary branches.
Follow-up questions
- How would you generalize the algorithm to k distinct cards drawn from a straight of length k + 1? Set window width
L = k + 1and iteratelowfrom1up to14 - L + 1, treating'0'as1solely whenlow == 1. ReturnVALUE_RANK[missing_values[0]]on the first window withlen(missing_values) == 1, running inO((14 - k) * k)time. - What changes if only 3 distinct cards are given and 2 ranks are missing from the 5-card straight? Several straights can now match even when gaps exist—for instance,
['4', '5', '6']fits2-6,3-7, and4-8. Keep the samelow = 1..10loop, checklen(missing_values) == 2, and either return the first matching pair[VALUE_RANK[m0], VALUE_RANK[m1]]for the lowest straight or collect all matching pairs if the caller wants every completion. - How should the function handle malformed inputs such as duplicate cards, unknown symbols, or hands that cannot form any straight? Guard the entry of
find_missing_rankwithlen(ranks) == 4,len(set(ranks)) == 4, andall(r in RANK_VALUE for r in ranks), raisingValueErrorwhenever any check fails. After those guards pass, any non-straight 4-card hand (such as['2', '5', '9', 'K']) misses at least two slots in everylow = 1..10window and triggers the trailingraise ValueError(...).
Follow-up questions
- How would you generalize the algorithm to k distinct cards drawn from a straight of length k + 1?
- What changes if only 3 distinct cards are given and 2 ranks are missing from the 5-card straight?
- How should the function handle malformed inputs such as duplicate cards, unknown symbols, or hands that cannot form any straight?
Similar questions
- Longest Consecutive Login Streaks
- Subset Next Greater Lookup
- Clockwise Spiral Traversal Around Grid Obstacles
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses