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 ranks 2 through 9.
  • 'T' denotes 10.
  • '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 straight A-2-3-4-5 (acting as value 1) or at the top of the broadway straight 10-J-Q-K-A (acting as value 14 above King). Straights never wrap past both ends (for instance, Q-K-A-2-3 is 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 both 6-7-8-9-10 and 7-8-9-10-J, or 2-3-4-5, which fits both A-2-3-4-5 and 2-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 ranks is 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 ranks may be unsorted.

Step-by-step walkthrough

  1. 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:

    1. Dual-role Ace without wrap-around: Ace acts as 1 in A-2-3-4-5 or as 14 in 10-J-Q-K-A, never bridging across both ends like Q-K-A-2-3.
    2. Four already-consecutive cards have no interior gap: In Example 1 (['7', '8', '9', 'T']), the missing card sits on an outer end, so both 6-7-8-9-10 (missing '6') and 7-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 to A-2-3-4-5 ('0'), and ['T', 'J', 'Q', 'K'] completes downward to 9-T-J-Q-K ('9').
  2. 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 a 1..14 integer 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_VALUE maps each symbol to its default numeric rank (2..14, mapping '0' -> 14), paired with card_value(rank, ace_is_low) which overrides '0' to 1 only when testing A-2-3-4-5. - VALUE_RANK converts any integer in 1..14 back to its symbol (mapping both 1 and 14 to '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]
    
  3. 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 our 1..14 scale, so low takes only 10 possible values (1 through 10):

    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, ..., 10 in ascending order:

    1. Map the 4 distinct input symbols into a set held_values (setting ace_is_low = (low == 1)). Since all 4 symbols are distinct, held_values always holds 4 distinct integers.
    2. Collect every integer in [low .. low + 4] absent from held_values.
    3. Whenever exactly 1 integer is absent from [low .. low + 4], the remaining 4 slots of that straight must all be in held_values—meaning all 4 held cards lie inside this straight, and the single absent value is our answer!

    Scanning low upward from 1 resolves every tie-breaker and boundary automatically: - For ['7', '8', '9', 'T'], low = 6 (6..10) runs before low = 7 (7..11), returning '6'. - For ['0', '2', '3', '4'], nothing sits below 1, so low = 1 (1..5) matches and returns '5'. - For ['J', 'Q', 'K', '0'], nothing sits above 14, so low = 10 (10..14) matches and returns 'T'.

  4. 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")
    
  5. 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'
    
  6. 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:

  1. For ['5', '0', '4', '2'] (Example 2), at low = 1 (frame 1..5) we map '0' to 1, forming held_values = {1, 2, 4, 5}. Notch 3 is the sole empty slot in 1..5, so we return VALUE_RANK[3] = '3'.
  2. For ['7', '8', '9', 'T'] (Example 1), frames 1..5 through 5..9 each miss at least two notches. At low = 6 (frame 6..10), held_values = {7, 8, 9, 10} misses only 6, 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 most 10 candidate frames, and each iteration builds a 4-item set and runs 5 O(1) set lookups (well under 100 primitive operations in the worst case).
  • Space: O(1). RANK_VALUE (13 keys) and VALUE_RANK (14 keys) have constant size, and each iteration allocates at most a 4-element set and a 5-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 below 1, so low = 1 (1..5) is the unique match and returns '5'.
  • Broadway straight (['J', 'Q', 'K', '0'] or ['T', 'Q', 'K', '0']): For low >= 2, '0' maps to 14, matching low = 10 (10..14) and returning 'T' or 'J'.
  • Missing card is Ace (['2', '3', '4', '5']): Frame 1..5 is tested before 2..6, returning '0'.
  • Four consecutive high cards (['T', 'J', 'Q', 'K']): Frame 9..13 is tested before 10..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 a set makes input ordering irrelevant.
  • Wrap-around combinations (K-A-2-3): Rejected automatically because Ace maps to either 1 (low == 1) or 14 (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 1 or fixed at 14: Fails either T-J-Q-K-A or A-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' to 1 when all remaining cards are <= 5 (else 14), then sort [v0, v1, v2, v3]. When v3 - v0 == 4, scan v0 .. v3 for the missing interior number; when v3 - v0 == 3, return 5 if v0 == 1, otherwise v0 - 1. It achieves the same O(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 + 1 and iterate low from 1 up to 14 - L + 1, treating '0' as 1 solely when low == 1. Return VALUE_RANK[missing_values[0]] on the first window with len(missing_values) == 1, running in O((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'] fits 2-6, 3-7, and 4-8. Keep the same low = 1..10 loop, check len(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_rank with len(ranks) == 4, len(set(ranks)) == 4, and all(r in RANK_VALUE for r in ranks), raising ValueError whenever 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 every low = 1..10 window and triggers the trailing raise ValueError(...).

Follow-up questions

Similar questions

More Temu interview questions

All 4 Temu questions →