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 outsidepossible_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], andguess[i]matches an unclaimed occurrence of that letter elsewhere intarget.0: miss —targethas no unclaimed occurrence ofguess[i]left.
Repeated letters are resolved in two strict passes:
- Exact matches first: mark
2at every indexiwhereguess[i] == target[i], consuming those character occurrences intarget. - Misplaced matches left to right: scan the remaining indices
0 .. 4in increasing order. Whenevertargetstill has at least one unused copy ofguess[i], mark1and consume one copy; otherwise mark0.
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:
- Immediate win: if
len(possible_words) == 1and that sole candidate belongs todictionary, returnpossible_words[0]directly so the puzzle finishes on this turn. - Worst-case bucket size: otherwise, for a candidate
guessindictionary, partitionpossible_wordsby the feedback tuple produced againstguess. Define that guess's worst-case remaining pool size as the maximum size among those feedback buckets. - Optimal choice: return the word in
dictionarywith 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_wordsanddictionaryhas length5and contains only lowercase ASCII letters ('a'–'z'). 1 <= len(possible_words) <= 10,0001 <= len(dictionary) <= 10,000- Runtime limit per call:
2seconds.
Step-by-step walkthrough
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 candidatesecretinpossible_wordsproduces 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 1The minimax objective is to choose the
guessindictionarywhose largest feedback bucket is as small as possible, breaking ties in favor of the lexicographically smallest word (and returningpossible_words[0]immediately when only1candidate remains).Score one guess against one secret in two passes
Scoring is straightforward when all five letters are distinct, and subtle when letters repeat. Exact
2matches take priority over misplaced1matches, and each letter copy insecretcan be claimed at most once.Why can't we score a pair in a single left-to-right loop? Look at
guess = "bleed"againstsecret = "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:
- Pass 1 (exact matches + count leftovers): wherever
guess[idx] == secret[idx], setfeedback[idx] = 2. Everywhere else, incrementleftover_counts[secret[idx]]so we know how many unmatched copies of each secret letter remain. - Pass 2 (misplaced matches from leftovers): scan left to right across non-
2positions; wheneverleftover_counts.get(guess[idx], 0) > 0, setfeedback[idx] = 1and decrementleftover_counts[guess[idx]]by1so 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)- Pass 1 (exact matches + count leftovers): wherever
Brute-force minimax: group candidates by feedback pattern
For any candidate
guessindictionary, we can compute its worst-case bucket directly from the definition:- Create an empty dictionary
group_countsmappingfeedback_tuple -> count. - For each
secretinpossible_words, computepattern = score_feedback(guess, secret)and add1togroup_counts[pattern]. - The largest value in
group_countsis this guess's worst-case remaining pool size.
Notice why we evaluate every word in
dictionary, not only words inpossible_words: when candidates share four of five positions (such as"brown","crown","drown","frown","grown"in Example 2), a probe word outsidepossible_wordslike"badge"tests three distinguishing consonants in a single guess!- Create an empty dictionary
Handle alphabetical tie-breaking and the single-candidate base case
In Example 1, both
"raven"and"rinse"split all three candidates into buckets of size1, 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 updatingbest_wordonly whenworst_size < best_worst(strictly smaller).Now check the single-candidate base case: when
len(possible_words) == 1(saypossible_words = ['crane']anddictionary = ['alone', 'crane', 'zebra']), every dictionary word produces a single bucket of size1. Without a base case, alphabetical tie-breaking would pick'alone'instead of winning immediately with'crane'! Returningpossible_words[0]wheneverlen(possible_words) == 1(and it is indictionary) guarantees termination.Speed up the search with early-exit bucket pruning
Suppose an alphabetically earlier guess already achieved
best_worst = 2. While scoring a later wordguess, what happens the instant any bucket ingroup_countsreaches2?- Its final worst-case bucket size will be at least
2. - Because we only replace
best_wordon a strict improvement (worst_size < 2), thisguesscan no longer win — even if every remaining candidate landed in a separate bucket!
Passing
cutoff = best_worstintolargest_group_sizelets us return immediately as soon asworst_size >= cutoff. Even better: once any guess achievesbest_worst = 1, every later dictionary word hitsworst_size = 1 >= 1on its very first candidate and stops inO(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- Its final worst-case bucket size will be at least
Trace Example 3 step by step
Let's trace Example 3 with
possible_words = ['otter', 'ether', 'enter', 'steer']and sorteddictionary = ['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 of1, and lose the tie to"enter"alphabetically.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. SortingdictionarytakesO(D log D)comparisons, and for each of theDguesses we score at mostPcandidate targets, wherescore_feedbackruns twoO(L)passes across the word. In practice, early-exit pruning skips most candidates once a smallbest_worstis found (oncebest_worst == 1, every subsequent guess stops after1candidate!). On turn 1 of a full10,000 x 10,000puzzle (10^8pairs), 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). Sortingdictionaryallocates anO(D)list of string references,group_countsstores at mostPdistinct 5-tuple keys at a time, andleftover_countsholds at mostLcharacter 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 size1. - Repeated letters in
guessorsecret("geeks"vs"spell","bleed"vs"paper","enter"vs"otter"): Pass 1 reserves all exact2matches before Pass 2 awards misplaced1s, and decrementingleftover_countsprevents one target letter from producing two1s. - Best probe lies outside
possible_words(Examples 1 and 2): Searching all ofdictionarydiscovers non-candidate splitters such as"raven"and"badge". - Ties in worst-case bucket size: Scanning
sorted(dictionary)and updating only whenworst_size < best_worstdeterministically picks the lexicographically smallest tied guess. - Shuffled input order: Sorting
dictionaryand counting unordered buckets makes the result independent of input ordering.
Common mistakes
- Checking
guess[idx] in secretfor misplaced letters: Ignores letter counts; in"enter"vs"otter", index0('e') must be0because"otter"'s only'e'is already matched at index3. - Scoring
2s and1s in one pass: An early1steals a letter copy needed for a later exact2match ("bleed"vs"paper"). - Searching only
possible_wordsinstead ofdictionary: 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 — becauselargest_group_sizeaborts as soon as a bucket reachesbest_worst, its true largest bucket could be much bigger! - Omitting the
len(possible_words) == 1base 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 = 243possible base-3 codessum(feedback[i] * 3^i)fitting in one byte (0 .. 242). Building aD x Dbytearraytable 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
Pis tiny): OncePdrops 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) andpossible_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 scalingDlinearly in theO(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 insidepossible_wordsadds a1 / Pchance 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_feedbackcall runs inO(k)time andO(min(k, alphabet_size))space, because Pass 1 and Pass 2 each scan thekindices once withO(1)dictionary lookups. Hashing thek-tuple intogroup_countsalso costsO(k), so the full minimax pass scales asO(D * P * k)time. Even though the total space of theoretical tile patterns grows exponentially as3^k, scoring one guess againstPcandidates populates at mostPnon-empty buckets, keepinggroup_countsbounded atO(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 - 1as a bitset (packing one boolean per candidate into the binary bits of a Pythonintor 64-bit word array so a single bitwiseANDfilters dozens of candidates in parallel). Precomputeexact_mask[idx][ch](candidates having characterchat indexidx) andat_least_mask[ch][m](candidates containing at leastmcopies ofch). For each guess, split active candidate bitsets across positions0 .. 4using bitwise&and~and count bucket sizes withint.bit_count(), cutting inner-loop work by ~30–64x while preserving early-exit pruning.
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?
- If word length generalizes from 5 characters to an arbitrary length k, how do single-pair scoring time and bucket storage scale with k?
- If the allowed vocabulary grew tenfold to 100,000 words, how could you accelerate candidate partitioning using precomputed bitmasks?
Similar questions
- Total Busy Duration and Peak Concurrent Rooms
- Maximize Non-Adjacent Totals on Lines and Trees
- Verify and Reconstruct IPv4 Strings
- Ocean Freight Container Packing Service with Hazmat Segregation
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger