Guess the Word

HardInteractive · Candidate Filtering · Minimax🧩 String ManipulationLeetCode #843 ↗Updated

Problem

A secret word was picked from words (distinct, each exactly 6 lowercase letters). Calling master.guess(w) returns -1 if w is not in the list, otherwise the number of positions where w and the secret hold the same letter. Implement findSecretWord(words, master) so that the secret itself is guessed within allowedGuesses calls.
Inputsecret = "bakery", words = ["banana","basket","bakery","rocket"]Outputsecret guessed within the limit
Inputguess("basket") when secret = "bakery"Output2 (b, a match)
Inputguess("zzzzzz")Output-1 (not in words)

1 ≤ words.length ≤ 100  ·  words[i].length == 6  ·  all words distinct  ·  secret ∈ words  ·  10 ≤ allowedGuesses ≤ 30

Try it yourself

Java
class Solution {
    public void findSecretWord(String[] words, Master master) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Every answer m tells you the secret is among the words that match your guess in exactly m positions. Choose the guess whose largest such group is smallest (minimax), so even the worst reply shrinks the candidates a lot.
PatternString Manipulation

Instinct Reading, comparing or rebuilding text character by character? Walk indices on a char[] and build output with a StringBuilder, never with + in a loop.

Memory hack Chars in an array, pointers on the ends, builder at the back - strings are just arrays wearing a costume.

Open the String Manipulation guide →

Approaches

Brute ForceGuess Every Word in Order

Time O(n · L)Space O(1)

The secret is somewhere in the list, so calling guess on each word in turn must hit it. The return value is used only to stop when it equals 6.

Java
public void findSecretWord(String[] words, Master master) {
    for (String w : words) {
        if (master.guess(w) == 6) return; // found it
    }
}

Always finds the secret, but may need up to 100 guesses — far over the limit.

At a glance

LevelApproachTimeSpace
Brute ForceGuess Every Word in OrderO(n · L)O(1)
BetterGuess a Candidate, Keep Only Consistent WordsO(g · n · L)O(n)
OptimalMinimax Guess over a Precomputed Match MatrixO(n2 · (L + g))O(n2)
Common pitfalls
  • Treating the reply as “common letters” — it counts same positions only.
  • Keeping words that match at least m positions instead of exactly m.
  • Guessing a word twice or a word outside the list — wastes a call.
Interview tips
  • Explain the elimination rule first; the guess-selection strategy is the follow-up.
  • Justify minimax: you optimise the worst reply because the secret is adversarial.
  • Mention the cheap alternative heuristic: pick the word sharing fewest 0-match partners.
Pattern
Minimax candidate elimination → interactive guessing where each reply partitions the remaining possibilities.
My notes saved in this browser