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 empty wordlist and max_guesses <= 0 defensively by returning None with 0 calls).
  • 1 <= L <= 10, where every string in wordlist has length L and consists of lowercase English letters 'a'–'z'.
  • All strings in wordlist are distinct, and in valid games secret is an element of wordlist.
  • max_guesses defaults to 10.

Step-by-step walkthrough

  1. Lock down the game rules and Python contract

    We receive wordlist, a list of n distinct lowercase strings all sharing the same length L, one of which is secret. On each turn we pass a word guess chosen from wordlist to match(guess), receiving k: the count of character indices i where guess[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 = 0
    

    We implement the clean contract in starter.py:

    • find_secret_word(wordlist, match, max_guesses=10) returns guess immediately as soon as match(guess) returns L, without calling match again.
    • It calls match at most max_guesses times, returning None if the turn budget runs out (or wordlist is 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 None
    
  2. Why scanning words sequentially runs out of budget

    Guessing wordlist[0], wordlist[1], wordlist[2] in order treats every response k < L as a bare "no" and discards the integer clue k. With 1,000 words and max_guesses = 10, linear scanning misses up to 990 possible secrets.

    To converge within ~10 turns, each miss must prune a large share of the surviving pool at once.

  3. Part 1: filter down to consistent candidates

    Maintain a list candidates of words still consistent with every clue seen so far (initially a copy of wordlist). Whenever we query guess and receive exact_matches = match(guess), secret is guaranteed to satisfy:

    count_matches(guess, secret) == exact_matches

    Any candidate whose exact-position overlap with guess is not equal to exact_matches is immediately ruled out. Notice the check is strict equality ==, not >=: in Example 2, when match("crane") returns 2, "crate" (4 matches with "crane") and "trace" (3 matches) are just as impossible as a word with 0 matches:

    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 matches
    

    Filtering 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.

  4. 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 yields k = 1, leaving all three alive!

    Before spending a turn on a candidate guess g, simulate every remaining candidate c and tally candidates across L + 1 buckets indexed by count_matches(g, c). Whichever candidate is actually secret, next round's candidates list 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 word g that minimizes max(bucket_counts).

    Two refinements make minimax substantially sharper:

    1. Score every word in wordlist, including already-eliminated words. A ruled-out word can act as a surgical splitter. Suppose candidates = ["ppp", "qqq", "rrr"] and wordlist also contains a ruled-out word "ppq":
      • Guessing "ppp" gets k = 0 against both "qqq" and "rrr", leaving a bucket of size 2.
      • Guessing "ppq" gets k = 2 vs "ppp", k = 1 vs "qqq", and k = 0 vs "rrr" — three buckets of size 1, guaranteeing the exact answer on the very next turn!
    2. Break ties toward live candidates (and fast-path len(candidates) == 1). When a live candidate ties a ruled-out word on largest_bucket, prefer the live candidate because it can win immediately on this turn. Comparing (largest_bucket, is_ruled_out) where is_ruled_out is 0 for live candidates and 1 otherwise 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
    
  5. What can and cannot be guaranteed about the turn limit

    State the theoretical limits clearly:

    • Adversarial word families can force up to 26 guesses under any algorithm. Take the 26 five-letter words "stema", "stemb", ..., "stemz". Every pair shares "stem", so any wrong guess returns k = 4 and eliminates only the single word just guessed.
    • Minimax never exceeds n guesses. Whenever |C| >= 2 candidates remain, guessing any live candidate places itself alone in bucket L and spreads the remaining |C| - 1 words across 0 .. L - 1, guaranteeing largest_bucket <= |C| - 1. Every miss therefore shrinks candidates by at least 1.
    • On diverse dictionaries, candidate pools shrink geometrically. All 81 four-letter words over {"a", "b", "c"} finish in at most 6 turns, and 80 random 6-letter words finish in at most 8 turns.
  6. Trace Example 1 end to end

    Trace wordlist = ["xyz", "xxx", "yyy", "zzz"] with secret = "zzz" and max_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 within 3 turns ("xxx" in 1, "xyz" in 2, "yyy" in 2, "zzz" in 3).

  7. Complete solution

    Assemble the helpers inside the bounded max_guesses loop:

    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 by O(G * n^2 * L)), where n is len(wordlist), |C| is the current count of surviving candidates, L is the word length, and G is max_guesses. On each turn, choose_guess scores all n words in wordlist against all |C| surviving candidates across L indices (O(n * |C| * L)), and filtering candidates afterward takes O(|C| * L). Because |C| shrinks geometrically on diverse lists, the full game usually costs less than 2.5 times Round 1 (~0.6 seconds in Python at n = 1,000, L = 10).
  • Space: O(n + L), storing at most n word references in candidates and candidate_set plus the temporary bucket_counts list of length L + 1.

Edge cases

  • Single-element dictionary (n = 1): len(candidates) == 1 triggers on Turn 1, calls match once, observes L, and returns immediately.
  • Zero budget (max_guesses <= 0) or empty dictionary: returns None right away without invoking match.
  • Single-letter variation families ("stema" .. "stemz"): every miss returns L - 1 and eliminates just 1 word. The loop halts cleanly after max_guesses queries and returns None without violating the budget.
  • One candidate remaining: a ruled-out word also yields a largest bucket of 1 against a single survivor, making the len(candidates) == 1 shortcut (and is_ruled_out tie-breaker) essential so we actually guess that survivor and win.

Common mistakes

  • Treating feedback like Wordle: match(guess) counts only exact index matches guess[i] == secret[i]; shared letters at different indices score 0.
  • Filtering with >= or <= rather than ==: if match(guess) returns k, secret matches guess at exactly k positions, so candidates sharing more than k positions are impossible too.
  • Calling match again after hitting L, or guessing outside wordlist: both break the oracle contract; return immediately on exact_matches == word_length.
  • Restricting probes strictly to candidates: already-eliminated words in wordlist can split surviving candidates into smaller buckets than any survivor itself (6 worst-case turns vs 9 across all 81 four-letter words over {"a", "b", "c"}).
  • Promising 10 turns on every valid input: 26-word families sharing L - 1 letters prove that no deterministic or randomized solver can beat 26 worst-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 sizes s — or minimize expected survivors sum(s^2) / |C|. Entropy trims average guesses slightly, whereas minimax directly guards a hard worst-case turn cap.
  • Precomputed n x n overlap table: Computing matches[i][j] once up front in O(n^2 * L) time (O(n^2) ints, ~1M entries for n = 1,000) replaces character loops on later turns with O(n * |C|) table lookups.
  • Positional character-frequency heuristic: Counting how often each character appears at each index 0 .. L - 1 across candidates and picking the word maximizing summed positional frequencies runs in O((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 inspect 10^10 pairs and time out. Instead, run the O((n + |C|) * L) positional letter-frequency heuristic (or score a random sample of ~200 candidate probes against ~1,000 sampled survivors, costing 2 * 10^5 comparisons) 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,296 codes) in at most 5 turns — but differ sharply in channel capacity per guess. Wordle returns per-index color tiles (3^5 = 243 possible patterns for L = 5), whereas our oracle returns a single integer in 0 .. L (L + 1 = 6 buckets for L = 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

Similar questions

More Moveworks interview questions

All 3 Moveworks questions →