Design a structure that supports addWord(word) and search(word), where the search pattern may contain '.' to match any single letter. Input is a LeetCode-style list of operations.
Insert words into a trie. Searching follows one child per letter; at a '.', it tries every child and succeeds if any branch matches the rest.
1class WordDictionary {2root = new TrieNode();3addWord(word: string): void {4let n = this.root;5for (const c of word) n = n.kids.get(c) ?? n.kids.set(c, new TrieNode()).get(c)!;6n.end = true;7}8search(word: string, i = 0, n = this.root): boolean {9if (i === word.length) return n.end;10if (word[i] === ".")11return [...n.kids.values()].some((k) => this.search(word, i + 1, k));12const next = n.kids.get(word[i]);13return !!next && this.search(word, i + 1, next);14}15}
Empty trie.
Space: play/pause · ←/→: step