Skip to content

843. Guess the Word 👎

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * // 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>& words, Master& master) {
    srand(time(nullptr));

    for (int i = 0; i < 10; ++i) {
      const string& guessedWord = words[rand() % words.size()];
      const int matches = master.guess(guessedWord);
      if (matches == 6)
        break;
      vector<string> updated;
      for (const string& word : words)
        if (getMatches(guessedWord, word) == matches)
          updated.push_back(word);
      words = std::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;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * // 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[] words, Master master) {
    Random rand = new Random();

    for (int i = 0; i < 10; ++i) {
      final String guessedWord = words[rand.nextInt(words.length)];
      final int matches = master.guess(guessedWord);
      if (matches == 6)
        break;
      List<String> updated = new ArrayList<>();
      for (final String word : words)
        if (getMatches(guessedWord, word) == matches)
          updated.add(word);
      words = 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;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# """
# 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:
    for _ in range(10):
      guessedWord = words[random.randint(0, len(words) - 1)]
      matches = master.guess(guessedWord)
      if matches == 6:
        break
      words = [
          word for word in words
          if sum(c1 == c2 for c1, c2 in zip(guessedWord, word)) == matches]