LeetCode Solutions

843. Guess the Word

Time: $O(n)$

Space: $O(n)$

			

/**
 * // 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:
  void findSecretWord(vector<string>& wordlist, Master& master) {
    srand(time(nullptr));  // Required

    for (int i = 0; i < 10; ++i) {
      const string& guessedWord = wordlist[rand() % wordlist.size()];
      const int matches = master.guess(guessedWord);
      if (matches == 6)
        break;
      vector<string> updated;
      for (const string& word : wordlist)
        if (getMatches(guessedWord, word) == matches)
          updated.push_back(word);
      wordlist = move(updated);
    }
  }

 private:
  int getMatches(const string& s1, const string& s2) {
    int matches = 0;
    for (int i = 0; i < s1.length(); ++i)
      if (s1[i] == s2[i])
        ++matches;
    return matches;
  }
};
			

/**
 * // 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 {
  public void findSecretWord(String[] wordlist, Master master) {
    Random rand = new Random();

    for (int i = 0; i < 10; ++i) {
      final String guessedWord = wordlist[rand.nextInt(wordlist.length)];
      final int matches = master.guess(guessedWord);
      if (matches == 6)
        break;
      List<String> updated = new ArrayList<>();
      for (final String word : wordlist)
        if (getMatches(guessedWord, word) == matches)
          updated.add(word);
      wordlist = updated.toArray(new String[0]);
    }
  }

  private int getMatches(final String s1, final String s2) {
    int matches = 0;
    for (int i = 0; i < s1.length(); ++i)
      if (s1.charAt(i) == s2.charAt(i))
        ++matches;
    return matches;
  }
}
			

# """
# 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, wordlist: List[str], master: 'Master') -> None:
    def getMatches(s1: str, s2: str) -> int:
      matches = 0
      for c1, c2 in zip(s1, s2):
        if c1 == c2:
          matches += 1
      return matches

    for _ in range(10):
      guessedWord = wordlist[randint(0, len(wordlist) - 1)]
      matches = master.guess(guessedWord)
      if matches == 6:
        break
      wordlist = [
          word for word in wordlist
          if getMatches(guessedWord, word) == matches]