Leetcode: 843. Guess the Word

Problem Statement

from typing import List

# """
# 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:
        N = len(wordlist[0])

        f = [Counter(w[i] for w in wordlist) for i in range(6)]
        wordlist.sort(reverse=True, key=lambda w: sum(f[i][c] for i, c in enumerate(w)))

        @cache
        def guess(s1, s2):
            ans = 0
            for a, b in zip(s1, s2):
                ans += 1 if a == b else 0
            return ans

        value = 0
        for _ in range(30):
            if not wordlist or value == N:
                break
            candidate = wordlist[0]
            value = master.guess(candidate)
            wordlist = [
                w for w in wordlist if w != candidate and guess(candidate, w) == value
            ]