KatInterview

873. Guess the Word

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Minimax Strategy

The problem asks us to find a secret word from a list of words within a limited number of guesses. This is an interactive problem where each guess gives us a piece of information—the number of exact matches with the secret word. The core challenge is to use this information to prune the search space as effectively as possible.

Solution

Guess the Word in Python

# """
# This is Master's API interface.
# You should not implement it, or speculate about its implementation
# """
# class Master:
#     def guess(self, word: str) -> int:

class Solution:
    def findSecretWord(self, words: List[str], master: 'Master') -> None:
        def count_matches(w1, w2):
            """Helper function to count matches between two words."""
            return sum(c1 == c2 for c1, c2 in zip(w1, w2))

        candidates = list(words)

        # We have at least 10 allowed guesses, a loop of 10-15 is safe.
        for _ in range(15):
            if not candidates:
                break

            # Minimax step to find the best word to guess.
            # The best word minimizes the size of the largest possible resulting candidate group.
            best_guess = ''
            min_max_group_size = float('inf')

            for guess_candidate in candidates:
                groups = collections.defaultdict(int)
                for word in candidates:
                    groups[count_matches(guess_candidate, word)] += 1
                
                max_group_size = 0
                for count in groups.values():
                    max_group_size = max(max_group_size, count)
                
                if max_group_size < min_max_group_size:
                    min_max_group_size = max_group_size
                    best_guess = guess_candidate

            # Make a guess with the best word found.
            matches = master.guess(best_guess)

            # If we found the secret word, we can return.
            if matches == 6:
                return

            # Filter the candidates list based on the number of matches.
            next_candidates = []
            for word in candidates:
                if count_matches(word, best_guess) == matches:
                    next_candidates.append(word)
            
            candidates = next_candidates

Guess the Word in Java

/**
 * // This is the Master's API interface.
 * // You should not implement it, or speculate about its implementation
 * interface Master {
 *     public int guess(String word) {}
 * }
 */
class Solution {
    // Helper function to count matches between two words.
    private int countMatches(String a, String b) {
        int matches = 0;
        for (int i = 0; i < a.length(); i++) {
            if (a.charAt(i) == b.charAt(i)) {
                matches++;
            }
        }
        return matches;
    }

    public void findSecretWord(String[] words, Master master) {
        List<String> candidates = new ArrayList<>(Arrays.asList(words));

        // We have at least 10 allowed guesses, so a loop of 10-15 should be safe.
        for (int i = 0; i < 15 && !candidates.isEmpty(); i++) {
            // Minimax step to find the best word to guess.
            // The best word minimizes the size of the largest possible resulting candidate group.
            String bestGuess = "";
            int minMaxGroupSize = Integer.MAX_VALUE;

            for (String guessCandidate : candidates) {
                int[] groups = new int[7]; // groups[k] = count of words with k matches
                for (String word : candidates) {
                    groups[countMatches(guessCandidate, word)]++;
                }

                int maxGroupSize = 0;
                for (int count : groups) {
                    maxGroupSize = Math.max(maxGroupSize, count);
                }

                if (maxGroupSize < minMaxGroupSize) {
                    minMaxGroupSize = maxGroupSize;
                    bestGuess = guessCandidate;
                }
            }

            // Make a guess with the best word found.
            int matches = master.guess(bestGuess);

            // If we found the secret word, we can return.
            if (matches == 6) {
                return;
            }

            // Filter the candidates list based on the number of matches.
            List<String> nextCandidates = new ArrayList<>();
            for (String word : candidates) {
                if (countMatches(word, bestGuess) == matches) {
                    nextCandidates.add(word);
                }
            }
            candidates = nextCandidates;
        }
    }
}

Guess the Word in C++

/**
 * // This is the Master's API interface.
 * // You should not implement it, or speculate about its implementation
 * class Master {
 *   public:
 *     int guess(string word);
 * };
 */
class Solution {
public:
    // Helper function to count matches between two words.
    int countMatches(const string& a, const string& b) {
        int matches = 0;
        for (int i = 0; i < a.length(); ++i) {
            if (a[i] == b[i]) {
                matches++;
            }
        }
        return matches;
    }

    void findSecretWord(vector<string>& words, Master& master) {
        vector<string> candidates = words;
        // We have at least 10 allowed guesses, so a loop of 10-15 should be safe.
        for (int i = 0; i < 15 && !candidates.empty(); ++i) {
            // Minimax step to find the best word to guess.
            // The best word minimizes the size of the largest possible resulting candidate group.
            string bestGuess = "";
            int minMaxGroupSize = INT_MAX;

            for (const string& guess_candidate : candidates) {
                vector<int> groups(7, 0); // groups[k] = count of words with k matches
                for (const string& word : candidates) {
                    groups[countMatches(guess_candidate, word)]++;
                }
                
                int maxGroupSize = 0;
                for (int count : groups) {
                    maxGroupSize = max(maxGroupSize, count);
                }

                if (maxGroupSize < minMaxGroupSize) {
                    minMaxGroupSize = maxGroupSize;
                    bestGuess = guess_candidate;
                }
            }

            // Make a guess with the best word found.
            int matches = master.guess(bestGuess);

            // If we found the secret word, we can return.
            if (matches == 6) {
                return;
            }

            // Filter the candidates list based on the number of matches.
            vector<string> next_candidates;
            for (const string& word : candidates) {
                if (countMatches(word, bestGuess) == matches) {
                    next_candidates.push_back(word);
                }
            }
            candidates = next_candidates;
        }
    }
};

Guess the Word in TypeScript

/**
 * // This is the Master's API interface.
 * // You should not implement it, or speculate about its implementation
 * class Master {
 *      guess(word: string): number {}
 * }
 */

function findSecretWord(words: string[], master: Master) {
    // Helper function to count matches between two words.
    const countMatches = (a: string, b: string): number => {
        let matches = 0;
        for (let i = 0; i < a.length; i++) {
            if (a[i] === b[i]) {
                matches++;
            }
        }
        return matches;
    };

    let candidates: string[] = [...words];

    // We have at least 10 allowed guesses, a loop of 10-15 is safe.
    for (let i = 0; i < 15 && candidates.length > 0; i++) {
        // Minimax step to find the best word to guess.
        // The best word minimizes the size of the largest possible resulting candidate group.
        let bestGuess = '';
        let minMaxGroupSize = Infinity;

        for (const guessCandidate of candidates) {
            const groups = new Map<number, number>();
            for (const word of candidates) {
                const matches = countMatches(guessCandidate, word);
                groups.set(matches, (groups.get(matches) || 0) + 1);
            }

            let maxGroupSize = 0;
            for (const count of groups.values()) {
                maxGroupSize = Math.max(maxGroupSize, count);
            }

            if (maxGroupSize < minMaxGroupSize) {
                minMaxGroupSize = maxGroupSize;
                bestGuess = guessCandidate;
            }
        }

        // Make a guess with the best word found.
        const matches = master.guess(bestGuess);

        // If we found the secret word, we can return.
        if (matches === 6) {
            return;
        }

        // Filter the candidates list based on the number of matches.
        const nextCandidates: string[] = [];
        for (const word of candidates) {
            if (countMatches(word, bestGuess) === matches) {
                nextCandidates.push(word);
            }
        }
        candidates = nextCandidates;
    }
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.