LeetCode 211: Design Add and Search Words Data Structure

link

Trie

If word has ".", we follow all available edges.

Say the longest word has length m.

OperationTimeSpace
insert\mathcal{O}(m)\mathcal{O}(m)
searchIf there are no dots: \mathcal{O}(m). If all are dots: \mathcal{O}(|\texttt{alphabet}|^m). Other cases should be in-between.\mathcal{O}(m)
class TrieNode:
    def __init__(self):
        self.end_of_word = False
        self.edges = {}

class WordDictionary:

    def __init__(self):
        self.root = TrieNode()

    def addWord(self, word: str) -> None:
        u = self.root
        for char in word:
            if char not in u.edges:
                u.edges[char] = TrieNode()
            u = u.edges[char]
        u.end_of_word = True

    def __search(self, u, word, i):
        if i == len(word):
            return u.end_of_word

        char = word[i]
        if char == ".":
            return any(
                self.__search(v, word, i+1) for v in u.edges.values()
            )    
        else:
            v = u.edges.get(char, None)
            if not v:
                return False
            return self.__search(v, word, i+1)

        
    def search(self, word: str) -> bool:
        return self.__search(self.root, word, 0)

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

Leave a comment