Problem 843

Abstract / Summary

One player picks a secret word and the other guesses trying to match it using feedback.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0843.py

class Solution:
    def findSecretWord(self, words: List[str], master: 'Master') -> None:
        while True:
            # try a random word
            candidate = random.choice(words)
            matches   = master.guess(candidate)
            if matches == 6:
                return

            # only those remain in wordlist that have the same number of matches
            next = []
            for w in words:
                same = sum([ a == b for a, b in zip(candidate, w) ])
                if same == matches:
                    next.append(w)
            words = next
16 lines | 600 bytes | submitted April 23, 2024 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 37% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Game Theory
  • Interactive
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “Mastermind” style guessing problem where a secret six-letter word must be discovered by repeatedly querying a Master interface. The algorithm iteratively narrows the candidate list based on the feedback from each guess, continuing until the secret word is found. The core loop selects a word at random from the current pool, asks the master for the number of matching positions, and then filters the pool to retain only those words that would produce the same match count with the chosen candidate. When the feedback indicates a perfect match (six correct letters), the function terminates.

Key Steps

The first important operation is the selection of a guess from the remaining word list. The code uses Python’s random.choice to pick an element without bias, ensuring that each iteration works with a potentially different candidate.

candidate = random.choice(words)

After a guess is made, the algorithm obtains the match count by invoking the guess method on the supplied master object. The returned integer represents how many characters are in the correct position relative to the secret word.

matches = master.guess(candidate)

A termination condition checks whether the match count equals the length of the word (six). If so, the secret has been identified and the function exits.

if matches == 6:
    return

The filtering phase constructs a new list containing only those words that would yield the same number of matches if they were compared with the current candidate. This is achieved by iterating over the existing words collection, computing the positional similarity using a generator expression inside sum, and appending qualifying entries to a temporary list.

next = []
for w in words:
    same = sum([a == b for a, b in zip(candidate, w)])
    if same == matches:
        next.append(w)
words = next

The loop then repeats, using the refined words list for the next random selection. This process continues until the secret word is guessed.

Edge Cases

The algorithm gracefully handles the situation where the initial word list contains duplicate entries. Because the filtering step evaluates each entry independently, duplicates that satisfy the match condition remain in the pool, preserving the statistical properties of the random selection.

When the feedback from master.guess is zero, the filter discards any word that shares a character in the same position with the candidate. This effectively eliminates a large portion of the search space in a single iteration, which is particularly useful when the candidate shares no positional similarity with the secret.

If the feedback value is intermediate (for example, three matches), the filter retains exactly those words that align with the candidate in the same three positions. This ensures that the algorithm never eliminates the true secret word, because the secret will always satisfy the equality check for the observed match count.

The loop’s termination condition (matches == 6) also covers the edge case where the secret word is guessed on the very first attempt. In that scenario, the function returns immediately without performing any filtering.

Performance Optimizations

A notable optimization is the use of a list comprehension inside sum to compute the number of matching characters between two words. By zipping the candidate and each word, the comparison operates in a tight, C-level loop, minimizing Python overhead.

same = sum([a == b for a, b in zip(candidate, w)])

The algorithm avoids recomputing match counts for pairs that have already been evaluated in previous iterations. Each iteration works only with the current reduced words list, which shrinks monotonically. Consequently, the number of comparisons performed in later rounds diminishes rapidly, leading to faster convergence.

Random selection via random.choice eliminates the need for sorting or ranking the candidate pool, which would introduce additional computational cost. By relying on randomness, the implementation sidesteps the overhead of more complex heuristic calculations while still achieving acceptable performance for typical input sizes.

Finally, the in-place reassignment words = next reuses the variable name for the filtered list, allowing Python’s garbage collector to reclaim the previous list without explicit deallocation. This keeps memory usage bounded by the size of the current candidate pool.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you are playing a fun guessing game where you have to find a secret word hidden inside a big pile of cards. Each card has a word written on it.

First, you pick one card from the pile at random to take a guess. You show this word to a friend who knows the secret answer, and they tell you how many letters match perfectly. If you get all six letters right, you win the game immediately.

If you do not win yet, you look at all the other cards you have not picked yet. You compare each of those cards to the one you just guessed. You are looking for cards that would have given you the exact same number of matches as the one you just tried. You throw away all the cards that do not match that count and keep only the ones that pass the test.

Now you have a smaller stack of cards to choose from for your next turn. You repeat this whole process, picking a random card from your new, smaller pile, over and over again. Each time you guess, you learn more information and get closer to finding the secret word until you finally guess it correctly.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6.5 | μ = 6.38 | σ = 1.42

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python
WalkCCC C++ Java Python
leetcode.ca C++ Java
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fengvyi C++
JoshCrozier JS
keineahnung2345 C++
ruoru Rust
suxrobGM C#
vli02 C
wisdompeak C++
AlgoMonster C++, Python, Java
WalkCCC C++, Python, Java
leetcode.ca C++, Java
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fengvyi C++
JoshCrozier JavaScript
keineahnung2345 C++
ruoru Rust
suxrobGM C#
vli02 C
wisdompeak C++
25 links | 16 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 solutions   April 23, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality