Minimum Guesses Against an Adversarial Word Host
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given words, a list of distinct lowercase English words that all have the exact same length. You are playing a letter-guessing game to pinpoint one secret word from words, except the game host plays adversarially: instead of fixing a single word before the game starts, the host dynamically maintains the subset of words in words that match every clue given so far and always chooses a valid response that prolongs the game as much as possible.
On each turn, you name one lowercase letter ('a'–'z') that you have not guessed yet. The host must respond with a positional pattern matching at least one surviving candidate word:
- Either the exact set of character indices where that letter occurs in some remaining candidate word, or
- An indication that the letter occurs nowhere, if at least one remaining candidate omits that letter.
All candidate words whose positions for that letter differ from the host's response are eliminated. The game finishes immediately as soon as only a single candidate word remains consistent with all revealed clues (no extra turn is spent announcing that final word, and if words already has at most 1 word, 0 guesses are needed).
Implement worst_case_guesses(words) to return the minimum number of letter guesses needed to guarantee identifying the word in the worst case when both you and the host play optimally.
Examples
Example 1
Input: words = ["dog", "dig", "fig"]
Output: 2
Explanation: Every candidate shares 'g' at index 2, so guessing 'g' eliminates nothing. Guessing 'd' splits "fig" (absent) from ["dog", "dig"] ('d' at index 0); if the host picks ["dog", "dig"], guessing 'o' (or 'i') separates them on turn 2. No single letter isolates all three words at once, so 2 guesses are optimal.
Example 2
Input: words = ["pop", "pot", "top", "tot"]
Output: 1
Explanation: Guessing 'p' on turn 1 produces four distinct positional patterns across the four candidates: indices (0, 2) for "pop", (0,) for "pot", (2,) for "top", and absent () for "tot". Whichever pattern the host reveals, only 1 candidate survives, finishing in 1 guess.
Example 3
Input: words = ["ax", "bx", "cx", "dx"]
Output: 3
Explanation: 'x' sits at index 1 in every word and reveals nothing. Each guess among 'a', 'b', 'c', and 'd' matches index 0 in only one word, allowing the host to answer "absent" twice in a row before a third guess separates the final two words.
Constraints
1 <= len(words) <= 151 <= len(words[i]) <= 10, and all words have the same length- Each string in
wordsconsists of lowercase English letters ('a'–'z') - All strings in
wordsare distinct
Step-by-step walkthrough
Understand the adversarial game
We are given a list of distinct lowercase words of equal length. In normal Hangman, the host picks one secret word at the beginning and sticks with it. Here the host is adversarial (often called "Evil Hangman"): the host does not commit to one word upfront. Whenever we guess a letter, the host can pick any response pattern that matches at least one remaining candidate word.
A response pattern for a guessed letter is the exact tuple of indices where that letter appears (for example,
(0, 2)in"aba", or()when the letter is absent):Candidates: ("dig", "dog", "fig") Guess 'f' -> pattern (0,) : ("fig",) -> 1 word left (done!) pattern () : ("dig", "dog") -> 2 words left (host picks this harder branch)Notice two simplifications right away:
- The game stops when 1 word remains, because play finishes immediately once at most one candidate remains consistent with all clues (we do not spend an extra turn reading out the word).
- We only need to track the remaining candidate words, not the set of already-guessed letters. Once a letter has been answered, every surviving word shares the exact same pattern for that letter, so guessing it a second time would keep all remaining words in a single group and never help us.
Why a greedy shortcut fails
A tempting shortcut is: "On each turn, pick the letter whose largest resulting group is as small as possible." Unfortunately, a larger group can be much easier to shatter on the very next guess than a smaller group!
Look at
["aa", "ba", "bc", "bd", "ca", "db", "dd"]:If we guess 'b' first (smallest worst-case group size = 3): pattern (0,) -> ("ba", "bc", "bd") [3 words, differing ONLY at index 1!] pattern (1,) -> ("db",) [1 word] pattern () -> ("aa", "ca", "dd") [3 words] Host picks ("ba", "bc", "bd"): every future letter isolates at most 1 word -> 2 more guesses (3 total). If we guess 'a' first (larger worst-case group size = 4): pattern (0, 1) -> ("aa",) [1 word] pattern (1,) -> ("ba", "ca") [2 words -> 1 more guess ('b') finishes] pattern () -> ("bc", "bd", "db", "dd") [4 words -> 1 guess ('d') gives (1,), (0,), (0,1), ()!] Every branch finishes in at most 1 more guess -> 2 guesses total!Because group size alone cannot tell us how many turns a group needs, we have to evaluate branches recursively.
Model the game with minimax
In a two-player game where we want fewer turns and the host wants more turns, the optimal answer follows a minimax rule (we take the minimum over our choices while our opponent takes the maximum over theirs):
- Base case: If
0or1candidate remains,0more guesses are needed. - Our choice (min): Try every letter that splits the current candidates into at least
2non-empty pattern groups. (A letter that leaves all words in1group wastes a turn and teaches nothing.) - Host's choice (max): For a fixed letter, the adversarial host picks whichever resulting group requires the maximum number of remaining guesses.
- Combine: That letter's worst-case cost is
1 + max_over_groups, and we pick the letter with the minimum such cost.
min_guesses(S) = 0 if |S| <= 1 min_guesses(S) = min over splitting letters c of: 1 + max over pattern groups g of (S, c) of: min_guesses(g)Why is a splitting letter guaranteed to exist whenever
|S| >= 2? Two distinct words of the same length must differ at some indexi; guessing the letter atword_1[i]putsword_1into a pattern containingiandword_2into a pattern withouti. Since every group is strictly smaller thanS, at most|S| - 1guesses are ever needed.- Base case: If
Group candidate words by revealed pattern
First we write two small helpers:
letter_positions(word, letter)scanswordand returns the tuple of indices whereletterappears (()if absent). We must record exact positions, not justTrue/Falseor a count: in["aab", "aba", "baa"],'a'appears twice in every word, yet its position tuples(0, 1),(0, 2), and(1, 2)separate all three words in one guess.partition_by_letter(candidates, letter)bucketscandidatesby that position tuple. If we sort the word list once at the very start,partition_by_letterpreserves relative order, so every group tuple is automatically sorted too and can be used directly as a dictionary key!
def letter_positions(word: str, letter: str) -> Tuple[int, ...]: """Return all indices where `letter` appears in `word`, or () if absent.""" positions = [] for index, char in enumerate(word): if char == letter: positions.append(index) return tuple(positions) def partition_by_letter(candidates: Tuple[str, ...], letter: str) -> List[Tuple[str, ...]]: """Split `candidates` into groups sharing the exact same revealed pattern for `letter`.""" # groups_by_pattern maps e.g. (0, 2) -> ["aba", ...] or () -> ["bcd", ...] groups_by_pattern: Dict[Tuple[int, ...], List[str]] = {} for word in candidates: pattern = letter_positions(word, letter) if pattern not in groups_by_pattern: groups_by_pattern[pattern] = [] groups_by_pattern[pattern].append(word) # Convert each list to a tuple; because `candidates` is already sorted, # every group stays sorted automatically and can be used as a memo key. result = [] for group_words in groups_by_pattern.values(): result.append(tuple(group_words)) return resultAdd memoization and early pruning
Guessing
'd'then'i'reaches the exact same surviving candidate set as guessing'i'then'd'. Memoization (caching each candidate tuple's answer in amemodictionary the first time we compute it) ensures we solve each reachable subset of words only once.We also add two clean, safe early-exit checks so we do not explore hopeless branches:
- Abandon a weak letter early: Suppose we already found a letter that guarantees
best_guesses = 2turns. While testing a new letter, if even one of its groups needs2more turns (1 + 2 >= 2), this new letter will take at least3turns in the worst case—so webreakout of its remaining groups right away! Checking larger groups first (groups.sort(key=len, reverse=True)) makes this cutoff trigger quickly. - Stop immediately at
1: Wheneverlen(candidates) >= 2,0guesses is impossible, so as soon as a letter achievesbest_guesses == 1, no other letter can beat it and webreakout of the letter loop.
def worst_case_guesses(words: List[str]) -> int: # Phase 1: Deduplicate and sort once so any subset of candidates has a single # canonical tuple representation regardless of the order letters were guessed. initial_candidates = tuple(sorted(set(words))) # memo maps a sorted candidate tuple -> minimum worst-case guesses needed memo: Dict[Tuple[str, ...], int] = {} def min_guesses(candidates: Tuple[str, ...]) -> int: # Base case: 0 or 1 consistent word left means the hidden word is identified. if len(candidates) <= 1: return 0 if candidates in memo: return memo[candidates] # Phase 2: Try every useful letter (we minimize; the host maximizes). # At most len(candidates) - 1 guesses are ever needed, so len(candidates) # is a strict integer upper bound on the optimal answer. best_guesses = len(candidates) # Only letters appearing in at least one candidate can possibly split the set; # a completely absent letter puts every word into () and teaches nothing. present_letters = sorted(set("".join(candidates))) for letter in present_letters: groups = partition_by_letter(candidates, letter) # Skip letters that produce a single pattern for all remaining words # (this includes previously guessed letters and shared fixed letters). if len(groups) < 2: continue # Check larger groups first so hard branches trigger early pruning sooner. groups.sort(key=len, reverse=True) worst_for_letter = 0 for group in groups: branch_guesses = min_guesses(group) if branch_guesses > worst_for_letter: worst_for_letter = branch_guesses # Pruning: if the host already has a response forcing >= best_guesses # total turns, this letter cannot beat our best letter so far. if 1 + worst_for_letter >= best_guesses: break if 1 + worst_for_letter < best_guesses: best_guesses = 1 + worst_for_letter # Two or more words always require at least 1 guess, so 1 is unbeatable. if best_guesses == 1: break memo[candidates] = best_guesses return best_guesses return min_guesses(initial_candidates)- Abandon a weak letter early: Suppose we already found a letter that guarantees
Trace Example 1 step by step
Let us trace
words = ["dog", "dig", "fig"]. Sorted,initial_candidates = ("dig", "dog", "fig"), andpresent_letters = ['d', 'f', 'g', 'i', 'o']:State: ("dig", "dog", "fig"), best_guesses starts at 3 letter 'd': group (0,) = ("dig", "dog") -> min_guesses(("dig", "dog")): letter 'i' splits into ("dig",) [0] and ("dog",) [0] -> returns 1 group () = ("fig",) -> returns 0 worst_for_letter = max(1, 0) = 1 -> 1 + 1 = 2 -> best_guesses becomes 2! letter 'f': largest group () = ("dig", "dog") -> cached in memo -> returns 1 1 + 1 >= best_guesses (2) -> pruned immediately! letter 'g': pattern (2,) for all 3 words -> 1 group -> skipped! letter 'i': largest group (1,) = ("dig", "fig") -> needs 1 guess ('d' or 'f') 1 + 1 >= best_guesses (2) -> pruned immediately! letter 'o': largest group () = ("dig", "fig") -> cached in memo -> returns 1 1 + 1 >= best_guesses (2) -> pruned immediately! Result: 2Notice how
memoreused("dig", "dog")and("dig", "fig")without re-solving them, and pruning skipped checking the smaller groups once a branch hit1 + 1 >= 2.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def letter_positions(word: str, letter: str) -> Tuple[int, ...]: """Return all indices where `letter` appears in `word`, or () if absent.""" positions = [] for index, char in enumerate(word): if char == letter: positions.append(index) return tuple(positions) def partition_by_letter(candidates: Tuple[str, ...], letter: str) -> List[Tuple[str, ...]]: """Split `candidates` into groups sharing the exact same revealed pattern for `letter`.""" # groups_by_pattern maps e.g. (0, 2) -> ["aba", ...] or () -> ["bcd", ...] groups_by_pattern: Dict[Tuple[int, ...], List[str]] = {} for word in candidates: pattern = letter_positions(word, letter) if pattern not in groups_by_pattern: groups_by_pattern[pattern] = [] groups_by_pattern[pattern].append(word) # Convert each list to a tuple; because `candidates` is already sorted, # every group stays sorted automatically and can be used as a memo key. result = [] for group_words in groups_by_pattern.values(): result.append(tuple(group_words)) return result def worst_case_guesses(words: List[str]) -> int: # Phase 1: Deduplicate and sort once so any subset of candidates has a single # canonical tuple representation regardless of the order letters were guessed. initial_candidates = tuple(sorted(set(words))) # memo maps a sorted candidate tuple -> minimum worst-case guesses needed memo: Dict[Tuple[str, ...], int] = {} def min_guesses(candidates: Tuple[str, ...]) -> int: # Base case: 0 or 1 consistent word left means the hidden word is identified. if len(candidates) <= 1: return 0 if candidates in memo: return memo[candidates] # Phase 2: Try every useful letter (we minimize; the host maximizes). # At most len(candidates) - 1 guesses are ever needed, so len(candidates) # is a strict integer upper bound on the optimal answer. best_guesses = len(candidates) # Only letters appearing in at least one candidate can possibly split the set; # a completely absent letter puts every word into () and teaches nothing. present_letters = sorted(set("".join(candidates))) for letter in present_letters: groups = partition_by_letter(candidates, letter) # Skip letters that produce a single pattern for all remaining words # (this includes previously guessed letters and shared fixed letters). if len(groups) < 2: continue # Check larger groups first so hard branches trigger early pruning sooner. groups.sort(key=len, reverse=True) worst_for_letter = 0 for group in groups: branch_guesses = min_guesses(group) if branch_guesses > worst_for_letter: worst_for_letter = branch_guesses # Pruning: if the host already has a response forcing >= best_guesses # total turns, this letter cannot beat our best letter so far. if 1 + worst_for_letter >= best_guesses: break if 1 + worst_for_letter < best_guesses: best_guesses = 1 + worst_for_letter # Two or more words always require at least 1 guess, so 1 is unbeatable. if best_guesses == 1: break memo[candidates] = best_guesses return best_guesses return min_guesses(initial_candidates)✅ Submit now — all tests should pass.
Intuition & how it works
Imagine playing Twenty Questions against a mischievous friend who refuses to write down a secret word at the start. Instead, they keep a hidden notepad of every word that still matches all the clues given so far, and whenever you guess a letter, they purposely give whichever valid clue leaves you with the hardest remaining puzzle. Because your friend always picks the toughest surviving group and you want to finish in as few turns as possible, this is a minimax game—a two-player search where you choose the move with the minimum cost while your opponent chooses the reply with the maximum cost.
Two obvious approaches fail here. First, a greedy rule that always picks the letter whose largest group is smallest can lose: a group of 4 words with rich letter variety can split into 4 singletons in 1 more guess, whereas a group of 3 words like "ba", "bc", "bd" forces you to peel off words one at a time. Second, a plain brute-force recursion that tracks the history of guessed letters re-solves the exact same subset of remaining words many times (guessing 'd' then 'i' leaves the exact same candidates as guessing 'i' then 'd'). By sorting the initial word list once and using memoization—caching each sorted tuple of remaining candidate words in a dictionary so it is solved only once—we compute exact optimal answers without redundant work.
Walk through ["pop", "pot", "top", "tot"] (Example 2):
- Start with sorted candidates
("pop", "pot", "top", "tot"). - Try guessing
'p':"pop"reveals(0, 2),"pot"reveals(0,),"top"reveals(2,), and"tot"reveals(). - Every single pattern group has size
1, which needs0further guesses! - Even the adversarial host's worst group needs
0more guesses, so1 + 0 = 1guess guarantees identifying the word.
Complexity
Let n be the number of words, L be the length of each word, sigma be the number of distinct letters appearing in the input (at most 26), and M be the number of distinct candidate subsets actually reached by the search.
- Time: O(M * sigma * n * L). Each reachable candidate tuple is evaluated and stored in
memoonce. Evaluating one state tries up tosigmadistinct letters, and partitioning up tonwords of lengthLby letter positions scansO(n * L)characters (sorting the at mostngroups takesO(n log n), which is dominated or matched by partitioning). How large canMbe? Every reachable subset is defined by the patterns revealed for some subset of thesigmaletters, giving at mostnequivalence classes per letter subset, soM <= min(2^n, n * 2^sigma). In the worst case (such asnsingle-letter words["a", "b", "c", ...], where every subset of words is reachable by hearing "absent"),Mis exponential, so exact minimax is suited for small or structured word sets rather than a 100,000-word dictionary. - Space: O(M * n). The
memodictionary stores up toMkeys, where each key is a tuple of up tonword references (the word strings themselves are shared in memory), plus recursion call-stack frames up to the game depth (at mostmin(n - 1, sigma)).
Edge cases
- Single word (or empty list): With
len(candidates) <= 1, the word is already uniquely known before we speak a single letter, so the function immediately returns0. - Two distinct words: Always returns
1, because two distinct equal-length words differ at some indexi, and guessingword_1[i]puts them into different pattern groups. - Repeated letters within a word:
["aab", "aba", "baa"]returns1because'a'sits at three distinct index tuples(0, 1),(0, 2), and(1, 2), even though'a'appears twice in every word. - Letters shared at identical positions: In
["abc", "abd", "abe"],'a'is at(0,)and'b'is at(1,)in every word; both producelen(groups) == 1and are skipped so we never waste turns on them. - One-letter words (
["a", "b", "c", "d"]): Guessing any letter splits1word from the remainingn - 1words; the host always says "absent" until the final two words, requiringn - 1guesses (3here). - Duplicate words in input: Although the statement promises distinct words,
set(words)removes duplicates upfront so identical words can never trap the recursion.
Common mistakes
- Checking only letter presence or letter count instead of exact indices: Treating
"ab"and"ba"as having the same response for'a'misses the positional information Hangman reveals and overcounts required guesses. - Adding
+1at the end to "name the final word": Oncelen(candidates) == 1, only one word is consistent with all clues, so0additional letter guesses are needed. - Using greedy min-max group size without recursion: Picking the letter that minimizes
max(len(g) for g in groups)fails on["aa", "ba", "bc", "bd", "ca", "db", "dd"](returns3instead of2). - Including
guessed_lettersin the memo key: Storing(candidates, guessed_letters)is correct in output but blows up cache misses becausekletters guessed ink!different orders createk!duplicate cache entries for the exact samecandidatestuple. - Forgetting to sort
wordsonce at the start: Without a canonical form—a single standard ordering so equal sets always produce identical tuples—the same subset of words could appear in different orders and miss the cache (though starting from one fixed list and preserving order during partitioning also keeps order consistent across a single call).
Alternative approaches
- Iterative-deepening budget check (
can_finish(candidates, budget)): Instead of computing the exact turn count directly, ask a yes/no question—"Can we guarantee finishing withinbudgetturns?"—forbudget = 0, 1, 2, ...and memoize(candidates, budget). It exits a letter on the first failing group and exits a state on the first winning letter, which works well when the answerhis tiny, but adds an(h + 1)factor to time and memory and repeats searches whenhis large (such asn - 1on one-letter words). Direct memoized minimax with1 + worst_for_letter >= best_guessespruning captures the same early-cutoff benefit while solving eachcandidatestuple only once. - Greedy or Shannon-entropy heuristics for huge dictionaries: For full-dictionary Evil Hangman (
n = 50,000), exact minimax is exponential. Practical solvers pick the letter that minimizesmax(len(g))or maximizes entropy (a measure from information theory of how evenly the candidates spread across pattern groups), giving a fast valid strategy whose worst-case depth is a close upper bound on the true optimum.
Follow-up questions
- How would you adapt the code to output the optimal opening letter as well as the full decision tree of follow-up guesses? Instead of storing just the integer
best_guessesinmemo[candidates], store a pair(best_guesses, best_letter)recording which letter achieved that minimum (and omit early pruning on groups if you want every reachable branch pre-populated, or recursively expand the chosen letter's groups afterward). Looking upmemo[initial_candidates]immediately gives the optimal opening guessbest_letter, and for whichever pattern response the host gives next, looking upmemo[next_group]gives our optimal next guess all the way down to single-word leaves. - Suppose the rules match traditional Hangman where only misses (letters absent from the word) count toward your penalty; how does the recurrence change? A guess now costs
1strictly on thepattern == ()branch and costs0on every branch where the letter appears at one or more indices. Inmin_guesses, add1 + min_guesses(group)whengroupcorresponds to pattern()and0 + min_guesses(group)for all non-empty patterns. The recursion still terminates cleanly without cycles because we only try letters withlen(groups) >= 2, meaning every branch strictly shrinkslen(candidates). - If the host secretly commits to one word uniformly at random upfront instead of adapting adversarially, how would you minimize the expected number of guesses? We want to minimize the expected (average) number of guesses rather than the worst case. Replace the host's
maxover groups with a probability-weighted average: for a candidate tupleSand letterc, a groupgoccurs with probabilitylen(g) / len(S), so the cost of guessingcbecomes1 + sum((len(g) / len(S)) * expected_guesses(g) for g in groups). Memoizingexpected_guesses(candidates)works identically, except we must evaluate every group ofc(until the partial weighted sum alone exceedsbest_expected) rather than pruning on a single worst branch.
Follow-up questions
- How would you adapt the code to output the optimal opening letter as well as the full decision tree of follow-up guesses?
- Suppose the rules match traditional Hangman where only misses (letters absent from the word) count toward your penalty; how does the recurrence change?
- If the host secretly commits to one word uniformly at random upfront instead of adapting adversarially, how would you minimize the expected number of guesses?
Similar questions
- Maximum Island Size After One Flip
- Score Exact and Misplaced Word Matches
- Rate-Limited Thread-Safe Key-Value Store
- Six-Part Operational Leadership Lightning Round
- Unexpected Technical Findings and Adapting Project Direction
- Walking Through Your Hardest Engineering Initiative
More Dropbox interview questions
- Walking Through Your Hardest Engineering Initiative Medium
- Unexpected Technical Findings and Adapting Project Direction Medium
- Design an Asynchronous Distributed File-System Crawler Medium Pro
- Six-Part Operational Leadership Lightning Round Medium Pro
- Maximum Island Size After One Flip Medium Pro
- Petabyte-Scale Cloud Object Storage Medium Pro
- Multi-Tenant File Recommendations with Real-Time ACLs Medium Pro
- Cloud File-Processing API and Async Job Engine Medium Pro
- End-to-End Project Deep Dive with Causal Impact Medium Pro
- Rate-Limited Thread-Safe Key-Value Store Medium Pro