Select Minimax Word Guesses from Tile Feedback

Hard · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Build the next-move selector for a five-letter word deduction puzzle. At each turn, you are given:

  • possible_words: the non-empty list of 5-letter lowercase words that still match every clue seen so far.
  • dictionary: the full list of 5-letter lowercase words legal to play as a guess (including probe words outside possible_words).

Clue Scoring Rules

Comparing a 5-letter guess against a 5-letter target yields a 5-tuple (c_0, c_1, c_2, c_3, c_4) where each position holds:

  • 2: exact hit — guess[i] == target[i].
  • 1: misplaced hit — guess[i] != target[i], and guess[i] matches an unclaimed occurrence of that letter elsewhere in target.
  • 0: miss — target has no unclaimed occurrence of guess[i] left.

Repeated letters are resolved in two strict passes:

  1. Exact matches first: mark 2 at every index i where guess[i] == target[i], consuming those character occurrences in target.
  2. Misplaced matches left to right: scan the remaining indices 0 .. 4 in increasing order. Whenever target still has at least one unused copy of guess[i], mark 1 and consume one copy; otherwise mark 0.

For instance, scoring guess = "speed" against target = "crepe" produces (0, 1, 2, 1, 0): index 2 ('e') claims 2 first, leaving one unused 'e' (at index 4 of "crepe") and one 'p' (at index 3), so 'p' at index 1 and 'e' at index 3 each receive 1 while 's' and 'd' receive 0.

Minimax Selection & Tie-Breaking

Implement get_best_guess(possible_words, dictionary) to pick the next guess using a one-step minimax rule:

  1. Immediate win: if len(possible_words) == 1 and that sole candidate belongs to dictionary, return possible_words[0] directly so the puzzle finishes on this turn.
  2. Worst-case bucket size: otherwise, for a candidate guess in dictionary, partition possible_words by the feedback tuple produced against guess. Define that guess's worst-case remaining pool size as the maximum size among those feedback buckets.
  3. Optimal choice: return the word in dictionary with the smallest worst-case remaining pool size. If multiple dictionary words tie for the smallest worst-case size, return the lexicographically smallest word ("a" before "z").
def get_best_guess(possible_words: List[str], dictionary: List[str]) -> str:
    pass

Examples

Example 1

Input:

possible_words = ["stone", "store", "stove"]
dictionary = ["stone", "store", "stove", "raven", "rinse", "trace", "plumb"]

Output:

"raven"

Explanation: Guessing "stone", "store", or "stove" leaves a worst-case bucket of size 2 (the two non-matching sto_e words both yield (2, 2, 2, 0, 2)). In contrast, probing "raven" tests 'r', 'v', and 'n' simultaneously, mapping "stone" to (0, 0, 0, 1, 1), "store" to (1, 0, 0, 1, 0), and "stove" to (0, 0, 1, 1, 0)—every bucket has size 1. "rinse" also achieves worst-case size 1, and "raven" wins the alphabetical tie ("raven" < "rinse").

Example 2

Input:

possible_words = ["brown", "crown", "drown", "frown", "grown"]
dictionary = [
    "brown", "crown", "drown", "frown", "grown",
    "badge", "craft", "drift", "fudge", "grind",
]

Output:

"badge"

Explanation: Any -rown guess leaves four candidates sharing (0, 2, 2, 2, 2) (worst case 4). "badge" tests 'b', 'd', and 'g' in one turn, shrinking the largest bucket ("crown" and "frown" both giving (0, 0, 0, 0, 0)) down to 2. "fudge" also reaches worst case 2, so lexicographical order selects "badge".

Example 3

Input:

possible_words = ["otter", "ether", "enter", "steer"]
dictionary = ["after", "otter", "ether", "enter", "steer", "reset", "three"]

Output:

"enter"

Explanation: Against "enter", duplicate-letter rules separate all four candidates into distinct buckets of size 1: "otter" gives (0, 0, 2, 2, 2) (its single 'e' is consumed at index 3), "ether" gives (2, 0, 1, 2, 2), "enter" gives (2, 2, 2, 2, 2), and "steer" gives (1, 0, 1, 2, 2) (its second 'e' lights up index 0). "ether" and "steer" also achieve worst case 1, and "enter" comes first alphabetically.

Constraints

  • Every string in possible_words and dictionary has length 5 and contains only lowercase ASCII letters ('a'–'z').
  • 1 <= len(possible_words) <= 10,000
  • 1 <= len(dictionary) <= 10,000
  • Runtime limit per call: 2 seconds.

Step-by-step walkthrough

  1. Understand the game, feedback buckets, and minimax goal

    We receive two word lists:

    • possible_words: candidate 5-letter target words that still satisfy every clue seen so far.
    • dictionary: all 5-letter words we are permitted to play (including probe words already ruled out as the hidden target).

    When we test a guess, every candidate secret in possible_words produces a 5-number clue tuple (2 = exact position, 1 = misplaced match, 0 = miss). Candidates that produce the same 5-tuple stay grouped together after the turn because that clue cannot tell them apart:

    Candidates: ["stone", "store", "stove"]
    
    Guess "stone":
      vs "stone" -> (2, 2, 2, 2, 2)  --- bucket of size 1
      vs "store" -> (2, 2, 2, 0, 2)  \__ bucket of size 2! (worst case = 2)
      vs "stove" -> (2, 2, 2, 0, 2)  /
    
    Guess "raven":
      vs "stone" -> (0, 0, 0, 1, 1)  --- bucket of size 1
      vs "store" -> (1, 0, 0, 1, 0)  --- bucket of size 1  (worst case = 1 -> better!)
      vs "stove" -> (0, 0, 1, 1, 0)  --- bucket of size 1
    

    The minimax objective is to choose the guess in dictionary whose largest feedback bucket is as small as possible, breaking ties in favor of the lexicographically smallest word (and returning possible_words[0] immediately when only 1 candidate remains).

  2. Score one guess against one secret in two passes

    Scoring is straightforward when all five letters are distinct, and subtle when letters repeat. Exact 2 matches take priority over misplaced 1 matches, and each letter copy in secret can be claimed at most once.

    Why can't we score a pair in a single left-to-right loop? Look at guess = "bleed" against secret = "paper":

    Index:          0   1   2   3   4
    secret:         p   a   p   e   r     (only ONE 'e', at index 3)
    guess:          b   l   e   e   d
    
    1-pass mistake: 0   0   1   ?   0     index 2 steals the only 'e' before index 3 sees the exact match!
    2-pass truth:   0   0   0   2   0     Pass 1 locks in 2 at index 3; zero 'e's remain for index 2!
    

    Splitting scoring into two passes makes repeated letters clean and exact:

    1. Pass 1 (exact matches + count leftovers): wherever guess[idx] == secret[idx], set feedback[idx] = 2. Everywhere else, increment leftover_counts[secret[idx]] so we know how many unmatched copies of each secret letter remain.
    2. Pass 2 (misplaced matches from leftovers): scan left to right across non-2 positions; whenever leftover_counts.get(guess[idx], 0) > 0, set feedback[idx] = 1 and decrement leftover_counts[guess[idx]] by 1 so the same copy is never claimed twice.
    def score_feedback(guess: str, secret: str) -> Tuple[int, ...]:
        """Compute Wordle feedback: 2 = Green (exact match), 1 = Yellow (elsewhere), 0 = Grey."""
        word_len = len(guess)
        feedback = [0] * word_len
        leftover_counts: Dict[str, int] = {}
    
        for idx in range(word_len):
            if guess[idx] == secret[idx]:
                feedback[idx] = 2
            else:
                secret_char = secret[idx]
                leftover_counts[secret_char] = leftover_counts.get(secret_char, 0) + 1
    
        for idx in range(word_len):
            if feedback[idx] == 2:
                continue
            guess_char = guess[idx]
            if leftover_counts.get(guess_char, 0) > 0:
                feedback[idx] = 1
                leftover_counts[guess_char] -= 1
    
        return tuple(feedback)
    
  3. Brute-force minimax: group candidates by feedback pattern

    For any candidate guess in dictionary, we can compute its worst-case bucket directly from the definition:

    1. Create an empty dictionary group_counts mapping feedback_tuple -> count.
    2. For each secret in possible_words, compute pattern = score_feedback(guess, secret) and add 1 to group_counts[pattern].
    3. The largest value in group_counts is this guess's worst-case remaining pool size.

    Notice why we evaluate every word in dictionary, not only words in possible_words: when candidates share four of five positions (such as "brown", "crown", "drown", "frown", "grown" in Example 2), a probe word outside possible_words like "badge" tests three distinguishing consonants in a single guess!

  4. Handle alphabetical tie-breaking and the single-candidate base case

    In Example 1, both "raven" and "rinse" split all three candidates into buckets of size 1, and "raven" wins because "raven" < "rinse". Likewise, "badge" beats "fudge" in Example 2, and "enter" beats "ether" and "steer" in Example 3.

    We get alphabetical tie-breaking automatically by iterating over sorted(dictionary) and updating best_word only when worst_size < best_worst (strictly smaller).

    Now check the single-candidate base case: when len(possible_words) == 1 (say possible_words = ['crane'] and dictionary = ['alone', 'crane', 'zebra']), every dictionary word produces a single bucket of size 1. Without a base case, alphabetical tie-breaking would pick 'alone' instead of winning immediately with 'crane'! Returning possible_words[0] whenever len(possible_words) == 1 (and it is in dictionary) guarantees termination.

  5. Speed up the search with early-exit bucket pruning

    Suppose an alphabetically earlier guess already achieved best_worst = 2. While scoring a later word guess, what happens the instant any bucket in group_counts reaches 2?

    • Its final worst-case bucket size will be at least 2.
    • Because we only replace best_word on a strict improvement (worst_size < 2), this guess can no longer win — even if every remaining candidate landed in a separate bucket!

    Passing cutoff = best_worst into largest_group_size lets us return immediately as soon as worst_size >= cutoff. Even better: once any guess achieves best_worst = 1, every later dictionary word hits worst_size = 1 >= 1 on its very first candidate and stops in O(1) time!

    def largest_group_size(guess: str, possible_words: List[str], cutoff: int) -> int:
        """Return the size of the largest feedback bucket for `guess`, stopping early at `cutoff`."""
        group_counts: Dict[Tuple[int, ...], int] = {}
        worst_size = 0
    
        for secret in possible_words:
            pattern = score_feedback(guess, secret)
            new_count = group_counts.get(pattern, 0) + 1
            group_counts[pattern] = new_count
    
            if new_count > worst_size:
                worst_size = new_count
                if worst_size >= cutoff:
                    return worst_size
    
        return worst_size
    
  6. Trace Example 3 step by step

    Let's trace Example 3 with possible_words = ['otter', 'ether', 'enter', 'steer'] and sorted dictionary = ['after', 'enter', 'ether', 'otter', 'reset', 'steer', 'three']:

    1. guess = "after" (cutoff = 5):
         vs "otter" -> (0, 0, 2, 2, 2)
         vs "ether" -> (0, 0, 1, 2, 2)
         vs "enter" -> (0, 0, 2, 2, 2)  <-- collides with "otter"! bucket size = 2
         vs "steer" -> (0, 0, 1, 2, 2)
       -> worst_size = 2 < 5  ==> best_word = "after", best_worst = 2
    
    2. guess = "enter" (cutoff = 2):
         vs "otter" -> (0, 0, 2, 2, 2)  ("otter"'s single 'e' is claimed at idx 3 -> idx 0 is 0!)
         vs "ether" -> (2, 0, 1, 2, 2)
         vs "enter" -> (2, 2, 2, 2, 2)
         vs "steer" -> (1, 0, 1, 2, 2)  ("steer" has a second 'e' -> idx 0 gets 1!)
       -> worst_size = 1 < 2  ==> best_word = "enter", best_worst = 1
    
    3. guesses "ether", "otter", "reset", "steer", "three" (cutoff = 1):
         each hits worst_size = 1 >= 1 after its 1st candidate and prunes immediately!
    

    The function returns "enter". Both "ether" and "steer" would also split all four candidates into buckets of 1, and lose the tie to "enter" alphabetically.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def score_feedback(guess: str, secret: str) -> Tuple[int, ...]:
        """Compute Wordle feedback: 2 = Green (exact match), 1 = Yellow (elsewhere), 0 = Grey."""
        word_len = len(guess)
        feedback = [0] * word_len
        # leftover_counts: maps each non-green secret letter to how many unused copies remain
        leftover_counts: Dict[str, int] = {}
    
        # Pass 1: Assign all Green (2) matches first so later Greens never lose a letter to Yellows.
        for idx in range(word_len):
            if guess[idx] == secret[idx]:
                feedback[idx] = 2
            else:
                secret_char = secret[idx]
                leftover_counts[secret_char] = leftover_counts.get(secret_char, 0) + 1
    
        # Pass 2: Assign Yellow (1) from left to right while unused copies of that letter remain.
        for idx in range(word_len):
            if feedback[idx] == 2:
                continue
            guess_char = guess[idx]
            if leftover_counts.get(guess_char, 0) > 0:
                feedback[idx] = 1
                leftover_counts[guess_char] -= 1
    
        return tuple(feedback)
    
    
    def largest_group_size(guess: str, possible_words: List[str], cutoff: int) -> int:
        """Return the size of the largest feedback bucket for `guess`, stopping early at `cutoff`."""
        # group_counts: maps each 5-tuple feedback pattern to how many candidates produce it
        group_counts: Dict[Tuple[int, ...], int] = {}
        worst_size = 0
    
        for secret in possible_words:
            pattern = score_feedback(guess, secret)
            new_count = group_counts.get(pattern, 0) + 1
            group_counts[pattern] = new_count
    
            if new_count > worst_size:
                worst_size = new_count
                # Pruning: once a bucket reaches `cutoff`, this guess cannot strictly beat `best_worst`.
                if worst_size >= cutoff:
                    return worst_size
    
        return worst_size
    
    
    def get_best_guess(possible_words: List[str], dictionary: List[str]) -> str:
        # Base case: if only one candidate secret remains, guess it directly to win immediately.
        if len(possible_words) == 1 and possible_words[0] in dictionary:
            return possible_words[0]
    
        best_word = ""
        # Start one above the maximum possible bucket size so the first guess is always accepted.
        best_worst = len(possible_words) + 1
    
        # Iterating in alphabetical order and updating only on strict `<` automatically
        # breaks ties in favor of the lexicographically smallest word.
        for guess in sorted(dictionary):
            worst_size = largest_group_size(guess, possible_words, best_worst)
            if worst_size < best_worst:
                best_worst = worst_size
                best_word = guess
    
        return best_word
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of playing "20 Questions," except each 5-letter guess gives back a 5-tile pattern of exact hits (2), misplaced hits (1), and misses (0). Any candidate targets in possible_words that produce the exact same 5-tuple land in the same bucket — after seeing that clue, you still cannot tell them apart. A minimax strategy (choosing the move whose worst possible outcome is as small as possible, as if an opponent always hands back whichever bucket leaves you the most remaining candidates) checks every legal word in dictionary, finds its largest feedback bucket, and picks the word with the smallest worst-case bucket (breaking ties alphabetically). To keep the search fast, we use pruning (stopping the evaluation of a candidate guess the instant any of its buckets reaches the best worst-case size already found, since it can no longer strictly beat our current winner).

Why do simpler approaches go wrong? Scoring letters in a single left-to-right pass mislabels repeated letters whenever an early 1 consumes the only copy of a letter needed by a later 2 (such as guessing bleed against paper). Restricting guesses to possible_words also overlooks much stronger probe words in dictionary — when candidates share almost all of their letters (like stone, store, stove), a non-candidate word testing fresh consonants (raven) separates all of them in a single turn.

Let's walk through Example 1 (possible_words = ['stone', 'store', 'stove']), comparing "stone" against "raven":

Guess "stone":
  score_feedback("stone", "stone") -> (2, 2, 2, 2, 2)  --- bucket size 1
  score_feedback("stone", "store") -> (2, 2, 2, 0, 2)  \__ bucket size 2 (worst = 2)
  score_feedback("stone", "stove") -> (2, 2, 2, 0, 2)  /

Guess "raven":
  score_feedback("raven", "stone") -> (0, 0, 0, 1, 1)  --- bucket size 1
  score_feedback("raven", "store") -> (1, 0, 0, 1, 0)  --- bucket size 1 (worst = 1!)
  score_feedback("raven", "stove") -> (0, 0, 1, 1, 0)  --- bucket size 1

"raven" guarantees at most 1 candidate remains regardless of which word was hidden, and beats "rinse" (which also achieves worst case 1) because "raven" comes earlier alphabetically.

Complexity

Let D be len(dictionary), P be len(possible_words), and L be the word length (L = 5).

  • Time: O(D log D + D * P * L) in the worst case. Sorting dictionary takes O(D log D) comparisons, and for each of the D guesses we score at most P candidate targets, where score_feedback runs two O(L) passes across the word. In practice, early-exit pruning skips most candidates once a small best_worst is found (once best_worst == 1, every subsequent guess stops after 1 candidate!). On turn 1 of a full 10,000 x 10,000 puzzle (10^8 pairs), pure Python per-call scoring would exceed a 2-second limit unless you cache the fixed opening move or precompute a compact byte table once per game.
  • Space: O(D + P). Sorting dictionary allocates an O(D) list of string references, group_counts stores at most P distinct 5-tuple keys at a time, and leftover_counts holds at most L character counts.

Edge cases

  • Single remaining candidate (len(possible_words) == 1): Returned directly so the solver wins immediately instead of picking an alphabetically earlier non-candidate word that also yields bucket size 1.
  • Repeated letters in guess or secret ("geeks" vs "spell", "bleed" vs "paper", "enter" vs "otter"): Pass 1 reserves all exact 2 matches before Pass 2 awards misplaced 1s, and decrementing leftover_counts prevents one target letter from producing two 1s.
  • Best probe lies outside possible_words (Examples 1 and 2): Searching all of dictionary discovers non-candidate splitters such as "raven" and "badge".
  • Ties in worst-case bucket size: Scanning sorted(dictionary) and updating only when worst_size < best_worst deterministically picks the lexicographically smallest tied guess.
  • Shuffled input order: Sorting dictionary and counting unordered buckets makes the result independent of input ordering.

Common mistakes

  • Checking guess[idx] in secret for misplaced letters: Ignores letter counts; in "enter" vs "otter", index 0 ('e') must be 0 because "otter"'s only 'e' is already matched at index 3.
  • Scoring 2s and 1s in one pass: An early 1 steals a letter copy needed for a later exact 2 match ("bleed" vs "paper").
  • Searching only possible_words instead of dictionary: Misses stronger probe words outside the remaining candidate pool and fails Examples 1 and 2.
  • Updating on worst_size <= best_worst: Not only reverses tie-breaking to the alphabetically largest word, it also breaks correctness with pruning — because largest_group_size aborts as soon as a bucket reaches best_worst, its true largest bucket could be much bigger!
  • Omitting the len(possible_words) == 1 base case: Traps a multi-turn caller in an infinite loop whenever the lone remaining answer is not the alphabetically earliest size-1 splitter.

Alternative approaches

  • Precomputed base-3 clue table (across turns): Every 5-tile pattern has 3^5 = 243 possible base-3 codes sum(feedback[i] * 3^i) fitting in one byte (0 .. 242). Building a D x D bytearray table once at game initialization lets every turn tally buckets via integer indexing (counts[code] += 1) with no string loops or tuple hashing.
  • Maximum entropy / minimum expected pool size: Instead of minimizing max(bucket_size), many practical solvers maximize entropy (an information-theory score measuring how evenly a guess distributes candidates across many buckets, sum(-(c/P) * log2(c/P))). Entropy lowers the average number of guesses, whereas minimax minimizes the worst-case pool after the next turn.
  • Multi-turn game-tree search (when P is tiny): Once P drops to a handful of words, looking 2–3 plies ahead minimizes the worst-case remaining turns to finish rather than just the next turn's bucket size.

Follow-up questions

  • Suppose probe guesses may come from an expanded vocabulary outside the list of legal secret answers—how does that affect candidate splitting and tie-breaking? Our function already accepts separate dictionary (allowed probes) and possible_words (eligible answers) lists, and Examples 1 and 2 already choose non-candidate probes ("raven" and "badge"). Allowing a broader probe vocabulary typically unlocks sharper multi-consonant splitters at the cost of scaling D linearly in the O(D * P * L) search. In multi-turn play, one refinement helps on ties: when two guesses share the exact same worst-case bucket size, preferring a word inside possible_words adds a 1 / P chance of winning immediately on the current turn.
  • If word length generalizes from 5 characters to an arbitrary length k, how do single-pair scoring time and bucket storage scale with k? A single score_feedback call runs in O(k) time and O(min(k, alphabet_size)) space, because Pass 1 and Pass 2 each scan the k indices once with O(1) dictionary lookups. Hashing the k-tuple into group_counts also costs O(k), so the full minimax pass scales as O(D * P * k) time. Even though the total space of theoretical tile patterns grows exponentially as 3^k, scoring one guess against P candidates populates at most P non-empty buckets, keeping group_counts bounded at O(P) entries (O(P * k) tuple storage).
  • If the allowed vocabulary grew tenfold to 100,000 words, how could you accelerate candidate partitioning using precomputed bitmasks? Encode any subset of candidate indices 0 .. P - 1 as a bitset (packing one boolean per candidate into the binary bits of a Python int or 64-bit word array so a single bitwise AND filters dozens of candidates in parallel). Precompute exact_mask[idx][ch] (candidates having character ch at index idx) and at_least_mask[ch][m] (candidates containing at least m copies of ch). For each guess, split active candidate bitsets across positions 0 .. 4 using bitwise & and ~ and count bucket sizes with int.bit_count(), cutting inner-loop work by ~30–64x while preserving early-exit pruning.

Follow-up questions

Similar questions

More Flexport interview questions

All 5 Flexport questions →