Secret Word Deduction from Positional Matches
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given wordlist, a collection of distinct lowercase strings that all have the exact same character length L. One hidden string inside wordlist has been chosen as secret.
To uncover secret, your function may repeatedly query an interactive oracle match(guess) -> int:
- Every guess passed to match must belong to wordlist.
- match(guess) returns the count of character indices 0 <= i < L where guess[i] == secret[i]. Characters that appear in both strings at different indices contribute 0.
Implement find_secret_word(wordlist, match, max_guesses=10) -> Optional[str]:
- As soon as match(guess) returns L, return guess immediately without invoking match any further.
- Invoke match at most max_guesses times in total.
- Return None if wordlist is empty, max_guesses <= 0, no consistent candidate remains, or max_guesses calls finish without hitting L.
Examples
Example 1
Input:
wordlist = ["xyz", "xxx", "yyy", "zzz"]
secret = "zzz"
max_guesses = 10
Output:
"zzz"
Explanation:
Guessing "xyz" first would be wasteful because "xxx", "yyy", and "zzz" all share 1 index with "xyz", leaving 3 candidates unsplit on k = 1. Guessing "xxx" instead returns match("xxx") == 0, eliminating "xyz" (1 match) and "xxx" (3 matches) and narrowing candidates to ["yyy", "zzz"]. Next, match("yyy") returns 0, leaving only ["zzz"], and match("zzz") returns 3 == L, identifying "zzz" in 3 calls.
Example 2
Input:
wordlist = ["crane", "crate", "slate", "trace", "flame"]
secret = "slate"
max_guesses = 10
Output:
"slate"
Explanation:
On turn 1, match("crane") returns 2 (matching 'a' at index 2 and 'e' at index 4). Comparing "crane" against every word gives match counts [5, 4, 2, 3, 2], so keeping only words with 2 matches eliminates "crane", "crate", and "trace", leaving ["slate", "flame"]. On turn 2, match("slate") returns 5 == L, returning "slate" immediately after 2 calls.
Constraints
1 <= len(wordlist) <= 1000(handle emptywordlistandmax_guesses <= 0defensively by returningNonewith0calls).1 <= L <= 10, where every string inwordlisthas lengthLand consists of lowercase English letters'a'–'z'.- All strings in
wordlistare distinct, and in valid gamessecretis an element ofwordlist. max_guessesdefaults to10.
Step-by-step walkthrough
Lock down the game rules and Python contract
We receive
wordlist, a list ofndistinct lowercase strings all sharing the same lengthL, one of which issecret. On each turn we pass a wordguesschosen fromwordlisttomatch(guess), receivingk: the count of character indicesiwhereguess[i] == secret[i].Unlike Wordle, a shared letter sitting at a different index contributes zero — only exact index matches count:
secret: f o x guess 1: f o g -> idx 0 ('f'=='f'), idx 1 ('o'=='o'), idx 2 ('g'!='x') -> k = 2 guess 2: x f o -> idx 0 ('x'!='f'), idx 1 ('f'!='o'), idx 2 ('o'!='x') -> k = 0We implement the clean contract in
starter.py:find_secret_word(wordlist, match, max_guesses=10)returnsguessimmediately as soon asmatch(guess)returnsL, without callingmatchagain.- It calls
matchat mostmax_guessestimes, returningNoneif the turn budget runs out (orwordlistis empty /max_guesses <= 0).
from typing import Callable, List, Optional def find_secret_word( wordlist: List[str], match: Callable[[str], int], max_guesses: int = 10, ) -> Optional[str]: return NoneWhy scanning words sequentially runs out of budget
Guessing
wordlist[0],wordlist[1],wordlist[2]in order treats every responsek < Las a bare "no" and discards the integer cluek. With1,000words andmax_guesses = 10, linear scanning misses up to990possible secrets.To converge within ~10 turns, each miss must prune a large share of the surviving pool at once.
Part 1: filter down to consistent candidates
Maintain a list
candidatesof words still consistent with every clue seen so far (initially a copy ofwordlist). Whenever we queryguessand receiveexact_matches = match(guess),secretis guaranteed to satisfy:count_matches(guess, secret) == exact_matchesAny candidate whose exact-position overlap with
guessis not equal toexact_matchesis immediately ruled out. Notice the check is strict equality==, not>=: in Example 2, whenmatch("crane")returns2,"crate"(4matches with"crane") and"trace"(3matches) are just as impossible as a word with0matches:candidates: ["crane", "crate", "slate", "trace", "flame"] (secret = "slate") guess = "crane" -> match("crane") returns 2 count_matches("crane", "crane") = 5 != 2 (drop: a missed guess always drops itself) count_matches("crane", "crate") = 4 != 2 (drop) count_matches("crane", "slate") = 2 == 2 (keep!) count_matches("crane", "trace") = 3 != 2 (drop) count_matches("crane", "flame") = 2 == 2 (keep!) next_candidates: ["slate", "flame"]Write the helper counting exact positional matches between two equal-length words:
def count_matches(word_a: str, word_b: str) -> int: """Return the number of positions i where word_a[i] == word_b[i].""" matches = 0 for i in range(len(word_a)): if word_a[i] == word_b[i]: matches += 1 return matchesFiltering is necessary, yet which word we probe next matters too: on 80 random 6-letter words, blindly picking
candidates[0]after each filter still requires up to 12 guesses.Part 2: 1-step minimax guess selection
Look at Example 1 (
wordlist = ["xyz", "xxx", "yyy", "zzz"]) to see why a careless first guess wastes a turn:guess matches vs [xyz, xxx, yyy, zzz] buckets (k: count) largest bucket "xyz" [3, 1, 1, 1] {3: 1, 1: 3} 3 (bad!) "xxx" [1, 3, 0, 0] {1: 1, 3: 1, 0: 2} 2 (better) "yyy" [1, 0, 3, 0] {1: 1, 3: 1, 0: 2} 2 (better) "zzz" [1, 0, 0, 3] {1: 1, 3: 1, 0: 2} 2 (better)Guessing
"xyz"against any of"xxx","yyy", or"zzz"always yieldsk = 1, leaving all three alive!Before spending a turn on a candidate guess
g, simulate every remaining candidatecand tallycandidatesacrossL + 1buckets indexed bycount_matches(g, c). Whichever candidate is actuallysecret, next round'scandidateslist will be one of those buckets. Under minimax (a decision rule that scores every action by its worst-case outcome and picks the action with the smallest worst case), we pick the wordgthat minimizesmax(bucket_counts).Two refinements make minimax substantially sharper:
- Score every word in
wordlist, including already-eliminated words. A ruled-out word can act as a surgical splitter. Supposecandidates = ["ppp", "qqq", "rrr"]andwordlistalso contains a ruled-out word"ppq":- Guessing
"ppp"getsk = 0against both"qqq"and"rrr", leaving a bucket of size2. - Guessing
"ppq"getsk = 2vs"ppp",k = 1vs"qqq", andk = 0vs"rrr"— three buckets of size1, guaranteeing the exact answer on the very next turn!
- Guessing
- Break ties toward live candidates (and fast-path
len(candidates) == 1). When a live candidate ties a ruled-out word onlargest_bucket, prefer the live candidate because it can win immediately on this turn. Comparing(largest_bucket, is_ruled_out)whereis_ruled_outis0for live candidates and1otherwise enforces both rules cleanly.
from typing import List def count_matches(word_a: str, word_b: str) -> int: matches = 0 for i in range(len(word_a)): if word_a[i] == word_b[i]: matches += 1 return matches def worst_case_left(guess: str, candidates: List[str]) -> int: """Return the largest candidate bucket size across all possible match counts.""" # bucket_counts[k] = how many remaining candidates share exactly k positions with guess bucket_counts = [0] * (len(guess) + 1) for candidate in candidates: exact_matches = count_matches(guess, candidate) bucket_counts[exact_matches] += 1 return max(bucket_counts) def choose_guess(wordlist: List[str], candidates: List[str]) -> str: """Pick the word from wordlist whose worst-case feedback leaves the fewest candidates.""" # Fast path: when only one suspect remains, guess it immediately to win if len(candidates) == 1: return candidates[0] candidate_set = set(candidates) best_word = wordlist[0] best_score = None # Search all of wordlist (even ruled-out words can split remaining candidates cleanly) for word in wordlist: largest_bucket = worst_case_left(word, candidates) # Tie-breaker: 0 for a live candidate (can win on this turn) beats 1 for a ruled-out word is_ruled_out = 0 if word in candidate_set else 1 score = (largest_bucket, is_ruled_out) if best_score is None or score < best_score: best_word = word best_score = score return best_word- Score every word in
What can and cannot be guaranteed about the turn limit
State the theoretical limits clearly:
- Adversarial word families can force up to
26guesses under any algorithm. Take the 26 five-letter words"stema","stemb", ...,"stemz". Every pair shares"stem", so any wrong guess returnsk = 4and eliminates only the single word just guessed. - Minimax never exceeds
nguesses. Whenever|C| >= 2candidates remain, guessing any live candidate places itself alone in bucketLand spreads the remaining|C| - 1words across0 .. L - 1, guaranteeinglargest_bucket <= |C| - 1. Every miss therefore shrinkscandidatesby at least1. - On diverse dictionaries, candidate pools shrink geometrically. All 81 four-letter words over
{"a", "b", "c"}finish in at most6turns, and 80 random 6-letter words finish in at most8turns.
- Adversarial word families can force up to
Trace Example 1 end to end
Trace
wordlist = ["xyz", "xxx", "yyy", "zzz"]withsecret = "zzz"andmax_guesses = 10:Initial state: candidates = ["xyz", "xxx", "yyy", "zzz"] Round 1: Scores (largest_bucket, is_ruled_out): "xyz" -> (3, 0) "xxx" -> (2, 0) <-- minimum score, chosen first "yyy" -> (2, 0) "zzz" -> (2, 0) Call match("xxx") -> returns 0 Keep candidates with 0 matches against "xxx": "xyz" (1), "xxx" (3), "yyy" (0 -> keep), "zzz" (0 -> keep) candidates = ["yyy", "zzz"] Round 2: Scores against ["yyy", "zzz"]: "xyz" -> matches [1, 1] -> (2, 1) "xxx" -> matches [0, 0] -> (2, 1) "yyy" -> matches [3, 0] -> (1, 0) <-- minimum score, chosen "zzz" -> matches [0, 3] -> (1, 0) Call match("yyy") -> returns 0 Keep candidates with 0 matches against "yyy": candidates = ["zzz"] Round 3: len(candidates) == 1 -> fast path picks "zzz" Call match("zzz") -> returns 3 == word_length -> return "zzz"!Every possible secret in
["xyz", "xxx", "yyy", "zzz"]finishes within3turns ("xxx"in 1,"xyz"in 2,"yyy"in 2,"zzz"in 3).Complete solution
Assemble the helpers inside the bounded
max_guessesloop:from typing import Callable, List, Optional def count_matches(word_a: str, word_b: str) -> int: """Return the number of positions i where word_a[i] == word_b[i].""" matches = 0 for i in range(len(word_a)): if word_a[i] == word_b[i]: matches += 1 return matches def worst_case_left(guess: str, candidates: List[str]) -> int: """Return the largest candidate bucket size across all possible match counts.""" # bucket_counts[k] = how many remaining candidates share exactly k positions with guess bucket_counts = [0] * (len(guess) + 1) for candidate in candidates: exact_matches = count_matches(guess, candidate) bucket_counts[exact_matches] += 1 return max(bucket_counts) def choose_guess(wordlist: List[str], candidates: List[str]) -> str: """Pick the word from wordlist whose worst-case feedback leaves the fewest candidates.""" # Fast path: when only one suspect remains, guess it immediately to win if len(candidates) == 1: return candidates[0] candidate_set = set(candidates) best_word = wordlist[0] best_score = None # Search all of wordlist (even ruled-out words can split remaining candidates cleanly) for word in wordlist: largest_bucket = worst_case_left(word, candidates) # Tie-breaker: 0 for a live candidate (can win on this turn) beats 1 for a ruled-out word is_ruled_out = 0 if word in candidate_set else 1 score = (largest_bucket, is_ruled_out) if best_score is None or score < best_score: best_word = word best_score = score return best_word def find_secret_word( wordlist: List[str], match: Callable[[str], int], max_guesses: int = 10, ) -> Optional[str]: """Find the secret word using at most max_guesses calls to match.""" if not wordlist or max_guesses <= 0: return None word_length = len(wordlist[0]) # candidates: words still consistent with every (guess, k) feedback seen so far candidates = list(wordlist) for _ in range(max_guesses): guess = choose_guess(wordlist, candidates) exact_matches = match(guess) # Return immediately on a full match so match() is never called again after winning if exact_matches == word_length: return guess # Keep only candidates that would have produced the exact same feedback exact_matches next_candidates = [] for word in candidates: if count_matches(guess, word) == exact_matches: next_candidates.append(word) candidates = next_candidates if not candidates: return None return None✅ Submit now — all tests should pass.
Intuition & how it works
Think of deducing secret like playing "20 Questions" over a lineup of suspects. Asking a lopsided question ("Is it zebra?") usually gets 0 matches and crosses off almost nobody besides zebra. A strong probe acts like a balanced splitter: whichever match count k (0 through L) match(guess) sends back, only a small slice of surviving suspects could have produced that exact k.
Trying words sequentially in list order fails because wordlist can contain 1,000 strings while max_guesses is around 10. Even filtering consistent candidates and naively picking candidates[0] stalls whenever candidates[0] shares the exact same overlap count with most remaining words, burning turns without partitioning the pool. Instead, we apply minimax — a decision rule that scores every candidate probe by its worst possible outcome (the size of its largest feedback bucket) and chooses the word whose worst bucket is smallest.
Trace Example 1 (wordlist = ["xyz", "xxx", "yyy", "zzz"], secret = "zzz"):
1. Round 1: Guessing "xyz" would return 1 against all three of "xxx", "yyy", and "zzz" (largest bucket = 3). Guessing "xxx" partitions the four words into match-count buckets {0: 2, 1: 1, 3: 1} (largest bucket = 2), so we choose "xxx". match("xxx") returns 0, narrowing candidates to ["yyy", "zzz"].
2. Round 2: Against ["yyy", "zzz"], "yyy" puts "yyy" in bucket 3 and "zzz" in bucket 0 (largest bucket = 1, and "yyy" is a live candidate). match("yyy") returns 0, leaving candidates = ["zzz"].
3. Round 3: With a single candidate left, we query "zzz", get match("zzz") == 3, and immediately return "zzz".
Complexity
- Time:
O(G * n * |C| * L)in the worst case (bounded byO(G * n^2 * L)), wherenislen(wordlist),|C|is the current count of surviving candidates,Lis the word length, andGismax_guesses. On each turn,choose_guessscores allnwords inwordlistagainst all|C|surviving candidates acrossLindices (O(n * |C| * L)), and filteringcandidatesafterward takesO(|C| * L). Because|C|shrinks geometrically on diverse lists, the full game usually costs less than2.5times Round 1 (~0.6seconds in Python atn = 1,000, L = 10). - Space:
O(n + L), storing at mostnword references incandidatesandcandidate_setplus the temporarybucket_countslist of lengthL + 1.
Edge cases
- Single-element dictionary (
n = 1):len(candidates) == 1triggers on Turn 1, callsmatchonce, observesL, and returns immediately. - Zero budget (
max_guesses <= 0) or empty dictionary: returnsNoneright away without invokingmatch. - Single-letter variation families (
"stema".."stemz"): every miss returnsL - 1and eliminates just 1 word. The loop halts cleanly aftermax_guessesqueries and returnsNonewithout violating the budget. - One candidate remaining: a ruled-out word also yields a largest bucket of
1against a single survivor, making thelen(candidates) == 1shortcut (andis_ruled_outtie-breaker) essential so we actually guess that survivor and win.
Common mistakes
- Treating feedback like Wordle:
match(guess)counts only exact index matchesguess[i] == secret[i]; shared letters at different indices score0. - Filtering with
>=or<=rather than==: ifmatch(guess)returnsk,secretmatchesguessat exactlykpositions, so candidates sharing more thankpositions are impossible too. - Calling
matchagain after hittingL, or guessing outsidewordlist: both break the oracle contract; return immediately onexact_matches == word_length. - Restricting probes strictly to
candidates: already-eliminated words inwordlistcan split surviving candidates into smaller buckets than any survivor itself (6worst-case turns vs9across all 81 four-letter words over{"a", "b", "c"}). - Promising 10 turns on every valid input: 26-word families sharing
L - 1letters prove that no deterministic or randomized solver can beat26worst-case turns on adversarial inputs.
Alternative approaches
- Maximum-entropy or minimum-expected-bucket scoring: Rather than minimizing
max(bucket_counts), maximize Shannon entropy — average information gained from the feedback distribution,-sum((s / |C|) * log2(s / |C|))across non-empty bucket sizess— or minimize expected survivorssum(s^2) / |C|. Entropy trims average guesses slightly, whereas minimax directly guards a hard worst-case turn cap. - Precomputed
n x noverlap table: Computingmatches[i][j]once up front inO(n^2 * L)time (O(n^2)ints, ~1M entries forn = 1,000) replaces character loops on later turns withO(n * |C|)table lookups. - Positional character-frequency heuristic: Counting how often each character appears at each index
0 .. L - 1acrosscandidatesand picking the word maximizing summed positional frequencies runs inO((n + |C|) * L)per round — fast enough for massive dictionaries, though weaker at breaking symmetric clusters.
Follow-up questions
- How would you adapt the solver if the dictionary grew to 100,000 candidate words? Full
O(n * |C| * L)minimax on Round 1 would inspect10^10pairs and time out. Instead, run theO((n + |C|) * L)positional letter-frequency heuristic (or score a random sample of ~200 candidate probes against ~1,000 sampled survivors, costing2 * 10^5comparisons) for the first one or two turns until|C|falls below ~1,000, then switch to exact minimax for the endgame. - How does exact-position integer feedback differ information-theoretically from classic Mastermind and Wordle? All three share the same filter-and-partition loop — where Donald Knuth (1977) showed 1-step minimax solves 4-peg, 6-color Mastermind (
1,296codes) in at most5turns — but differ sharply in channel capacity per guess. Wordle returns per-index color tiles (3^5 = 243possible patterns forL = 5), whereas our oracle returns a single integer in0 .. L(L + 1 = 6buckets forL = 5), packing far fewer bits of information into each turn. - Does 1-step minimax still hold up if an adaptive judge swaps the secret word mid-game whenever multiple candidates remain consistent? Yes: because 1-step minimax already assumes the oracle responds with whichever feedback bucket keeps the largest number of surviving candidates alive, an adaptive adversary cannot force a larger single-turn survivor pool than minimax already budgeted for. Randomizing guesses lowers expected turns against a fixed hidden word, but offers zero extra leverage against an adversary who chooses the bucket after seeing your guess.
Follow-up questions
- How would you adapt the solver if the dictionary grew to 100,000 candidate words?
- How does exact-position integer feedback differ information-theoretically from classic Mastermind and Wordle?
- Does 1-step minimax still hold up if an adaptive judge swaps the secret word mid-game whenever multiple candidates remain consistent?
Similar questions
- Word-Set Jaccard Index of Two Strings
- Vehicle Rental Search and Reservation Platform
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance