Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Guess the Word

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "843" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given an array of unique strings words where words[i] is six letters long. One word of words was chosen as a secret word. You are also given the helper object Master. You may call Master.guess(word) where word is a six-letter-long string, and it must be from words. Master.guess(word) returns: -1 if word is not from words, or an integer representing the number of exact matches (value and position) of your guess to the secret word. There is a parameter allowedGuesses for each test case where allowedGuesses is the maximum number of times you can call Master.guess(word). For each test case, you should call Master.guess with the secret word without exceeding the maximum number of allowed guesses. You will get: "Either you took too many guesses, or you did not find the secret word." if you called Master.guess more than allowedGuesses times or if you did not call Master.guess with the secret word, or "You guessed the secret word correctly." if you called Master.guess with the secret word with the number of calls to Master.guess less than or equal to allowedGuesses. The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method). Example 1: Input: secret = "acckzz", words = ["acckzz","ccbazz","eiowzz","abcczz"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: master.guess("aaaaaa") returns -1, because "aaaaaa" is not in wordlist. master.guess("acckzz") returns 6, because "acckzz" is secret and has all 6 matches. master.guess("ccbazz") returns 3, because "ccbazz" has 3 matches. master.guess("eiowzz") returns 2, because "eiowzz" has 2 matches. master.guess("abcczz") returns 4, because "abcczz" has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case. Example 2: Input: secret = "hamada", words = ["hamada","khaled"], allowedGuesses = 10 Output: You guessed the secret word correctly. Explanation: Since there are two words, you can guess both. Constraints: 1 <= words.length <= 100 words[i].length == 6 words[i] consist of lowercase English letters. All the strings of wordlist are unique. secret exists in words. 10 <= allowedGuesses <= 30

Explanation

Here's a breakdown of the solution:

  • Minimax Strategy: The core idea is to use a minimax strategy to reduce the search space efficiently. For each word in the remaining candidate list, we simulate guessing it and then partitioning the remaining words based on the number of matches. We choose the word that minimizes the maximum size of these partitions. This helps us narrow down the possibilities rapidly.
  • Match Calculation: We need an efficient way to compute the number of matches between two words. This function compares the words character by character and counts the matches.
  • Iterative Refinement: We repeat the guessing and filtering process until we find the secret word.

  • Runtime & Storage Complexity:

    • Runtime Complexity: O(N K L), where N is the number of words, K is the number of guesses (worst case close to the allowedGuesses), and L is the length of each word (6 in this case).
    • Storage Complexity: O(N), primarily for storing the list of remaining candidate words.

Code

    class Master:
    def guess(self, word: str) -> int:
        """
        This is the master's API.
        You should not implement it, or guess any internal implementation.
        The following explains how to use the Master API.

        master.guess(word) returns:
            -1 if the word is not in the wordlist,
             or an integer representing the number of exact matches (value and position) of your guess to the secret word.
        """
        pass

class Solution:
    def findSecretWord(self, words: list[str], master: 'Master') -> None:

        def matches(word1, word2):
            match_count = 0
            for i in range(len(word1)):
                if word1[i] == word2[i]:
                    match_count += 1
            return match_count

        def solve(candidates):
            if not candidates:
                return  # Should never happen given the problem constraints

            if len(candidates) == 1:
                master.guess(candidates[0])
                return

            best_guess = None
            min_max_partition_size = float('inf')

            for guess_word in candidates:
                max_partition_size = 0
                for match_count in range(7):
                    partition_size = 0
                    for candidate in candidates:
                        if matches(guess_word, candidate) == match_count:
                            partition_size += 1
                    max_partition_size = max(max_partition_size, partition_size)

                if max_partition_size < min_max_partition_size:
                    min_max_partition_size = max_partition_size
                    best_guess = guess_word

            match_val = master.guess(best_guess)

            if match_val == 6:
                return

            new_candidates = [word for word in candidates if matches(best_guess, word) == match_val]
            solve(new_candidates)

        solve(words)

More from this blog

C

Chatmagic blog

2894 posts