Minimize Expected Candidates with Position-Match Feedback
Math & Bit ManipulationAuto-graded · 27 test casesLast updated
Tests ability to model a greedy partitioning strategy using bitmask bucketing to minimize expected remaining candidates under green-only feedback.
Problem Description
You are building a solver for a restricted word-guessing game. The game works like this: there is a secret word drawn uniformly at random from a fixed word list. You pick a guess from that same list, and for each position you learn whether your guess matches the secret exactly at that position (a "hit"). Positions that do not match give you no information at all — you cannot tell whether the letter is absent or simply in the wrong place.
After seeing the hit pattern, you eliminate every word that could not have produced it. Your goal is to choose the guess that leaves the fewest candidates on average.
Write a function optimal_word_guess(words) that accepts the word list and returns the single best guess according to this criterion.
Feedback and Filtering Rules
- Given a guess
gand a secrets, positioniis a hit wheng[i] == s[i]. - The pattern for a (guess, secret) pair is the set of hit positions.
- After a guess, only words whose pattern against the guess matches the secret's pattern remain in play.
- Every word in the list is equally likely to be the secret.
Scoring a Guess
Because every word is equally likely, the expected number of candidates remaining after guess g is:
E[remaining | g] = (1 / n) * sum over all secrets s of |bucket(g, s)|
where bucket(g, s) is the set of words that share the same hit pattern as s against g, and n is the total number of words.
Equivalently, if the hit patterns partition the word list into groups of sizes k_1, k_2, …, then:
E[remaining | g] = (k_1² + k_2² + … ) / n
Since n is the same for every guess, minimizing the expected remaining count is the same as minimizing the sum of squared group sizes.
What to Return
Return the word from words that produces the smallest sum of squared group sizes. If two or more words tie on this score, return whichever comes first in lexicographic order.
Constraints
1 <= len(words) <= 2000- All words have the same length
L, where1 <= L <= 10. - Every word consists of lowercase English letters.
- The returned word must itself be an element of
words.
Examples
Example 1
Input: optimal_word_guess(['aba', 'aca', 'ada'])
Output: 'aba'
Example 2
Input: optimal_word_guess(['a', 'b', 'c'])
Output: 'a'
Example 3
Input: optimal_word_guess(['all', 'ill', 'ell', 'add'])
Output: 'add'
Hints
Hint 1
For a fixed guess, every secret maps to a hit pattern — the bitmask of positions where they agree. Words with the same bitmask are indistinguishable after that guess, so they form a bucket. The expected remaining count depends only on the sizes of these buckets.
Hint 2
You don't need floating-point division to compare expected values across guesses. Because n is constant, minimizing E[remaining] is the same as minimizing the integer sum of squared bucket sizes — compute that integer score directly.
Hint 3
To break ties in favor of the lexicographically smallest word, iterate over guesses in sorted order and update the best candidate only on a strictly smaller score (not ≤).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight: buckets and squared sizes
Fix a candidate guess g. Every word in the list, treated as a possible secret, produces a hit pattern — the subset of positions where the guess and the secret agree. Encode each pattern as a bitmask: bit i is set when position i is a hit. Words that share the same bitmask are in the same bucket: after the guess they are completely indistinguishable.
If the secret lands in a bucket of size k, then k words remain as candidates. The probability of landing in that bucket is k / n, so its contribution to the expected remaining count is (k / n) · k = k² / n. Summing over all buckets:
E[remaining | g] = (Σ k²) / n
Since n is identical for every guess, minimising the expectation is the same as minimising the integer sum of squared bucket sizes. Working with integers avoids any floating-point comparison issues.
Algorithm
- Deduplicate the word list and sort it lexicographically. Iterating in this order means the first time a new minimum score is found, the corresponding word is already the lexicographically smallest one that achieves it.
- For each candidate guess, loop over every word in the original list (each is an equally likely secret), compute the hit-pattern bitmask in O(L) time, and increment the appropriate bucket counter.
- Compute the score as the sum of squared bucket sizes.
- Keep track of the best (lowest) score seen so far; update only on a strict improvement to preserve the lexicographic tie-break.
Why it is correct
- The bitmask faithfully encodes the feedback: two secrets produce the same bitmask against a guess if and only if they produce identical feedback, which means the solver cannot distinguish them. That is exactly what defines a bucket.
- The expectation identity
Σ k² / nfollows directly from the equal-probability assumption and the bucket structure — no approximation is involved. - Scanning guesses in sorted order with a strict
<update guarantees that ties resolve to the lexicographically first word. - Repeated words in the input are treated as separate equally likely secrets (correct per the problem statement), but as the same guess (handled by deduplication).
Edge cases
- Single word: one bucket of size 1, score = 1. That word is returned.
- All words identical: one distinct guess, score = n². It is returned.
- L = 1: patterns are either a full match or no match; the algorithm handles this without modification.
- All-zero pattern (no hits anywhere): a valid bucket like any other.
Complexity
- Time: O(n² · L). There are at most
ndistinct guesses; for each,nsecrets are evaluated withLcharacter comparisons. At the problem limits that is 2 000 × 2 000 × 10 = 4 × 10⁷ basic operations. - Space: O(min(n, 2^L)) for the bucket dictionary, which is reused across guesses. With L ≤ 10 there are at most 1 024 distinct bitmasks. The sorted guess list adds O(n · L).
Reference solution
from typing import List
def optimal_word_guess(words: List[str]) -> str:
n = len(words)
length = len(words[0])
best_word = None
best_score = None
# Iterate over distinct guesses in lexicographic order so the first
# strictly minimal score automatically captures the lex-smallest tie.
for guess in sorted(set(words)):
# Build a bucket count keyed by the hit-pattern bitmask.
buckets: dict[int, int] = {}
for secret in words: # every word is an equally likely secret
pattern = 0
for i in range(length):
if guess[i] == secret[i]:
pattern |= 1 << i # bit i set = position i is a hit
buckets[pattern] = buckets.get(pattern, 0) + 1
# n * E[remaining | guess] = sum of squared bucket sizes.
# Comparing this integer across guesses is equivalent to comparing
# the true expected values, so no division is needed.
score = sum(size * size for size in buckets.values())
if best_score is None or score < best_score:
best_score = score
best_word = guess
return best_word