LeetCode 843: Guess the Word Solution

Master LeetCode problem 843 (Guess the Word), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

  • We can solve this problem using the minimax algorithm combined with a heuristic function to minimize the number of incorrect guesses.
  • The basic idea is to select a word from the list of words and use the feedback from the Master.guess() method to eliminate other words that do not match the feedback.
  • We keep track of the count of exact matches between the guessed word and the secret word to guide our next guess.
  • By selecting the next guess intelligently based on the feedback received, we can minimize the number of guesses required to find the secret word. :

Solution Code

import java.util.*;

class Solution {
    public void findSecretWord(String[] wordlist, Master master) {
        List<String> words = new ArrayList<>(Arrays.asList(wordlist));
        
        for (int i = 0; i < 10; i++) {
            String guess = getBestGuess(words);
            int match = master.guess(guess);
            if (match == 6) {
                return;
            }
            words = filterWords(words, guess, match);
        }
    }
    
    private String getBestGuess(List<String> words) {
        return words.get((int) (Math.random() * words.size()));
    }
    
    private List<String> filterWords(List<String> words, String guess, int match) {
        List<String> filtered = new ArrayList<>();
        for (String word : words) {
            if (countMatches(word, guess) == match) {
                filtered.add(word);
            }
        }
        return filtered;
    }
    
    private int countMatches(String word1, String word2) {
        int count = 0;
        for (int i = 0; i < word1.length(); i++) {
            if (word1.charAt(i) == word2.charAt(i)) {
                count++;
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 843 (Guess the Word)?

This page provides optimized solutions for LeetCode problem 843 (Guess the Word) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 843 (Guess the Word)?

The time complexity for LeetCode 843 (Guess the Word) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 843 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 843 in Java, C++, or Python.

Back to LeetCode Solutions