Add and Search Words

MediumTrieLeetCode 211 ↗World 9-12
0:00 / 0:00

Store words in a trie and search patterns where a dot matches any letter, branching into every child only when you meet a dot.

▼

The problem

LeetCode 211, Design Add and Search Words Data Structure (Medium). Build a WordDictionary with addWord(word) and search(word), where the search pattern may contain dots and a dot matches any one letter.

Example: add bat, bag, dad (bat and bag share B and A).

TRY IT ON LEETCODE ▶

The solution

class Node:
    def __init__(self): self.kids, self.end = {}, False
class WordDictionary:
    def __init__(self): self.root = Node()
    def addWord(self, word):
        node = self.root
        for ch in word:
            node = node.kids.setdefault(ch, Node())
        node.end = True
    def search(self, word):
        def dfs(node, i):
            if i == len(word):
                return node.end
            if word[i] == '.':
                return any(dfs(k, i + 1) for k in node.kids.values())
            kid = node.kids.get(word[i])
            return kid is not None and dfs(kid, i + 1)
        return dfs(self.root, 0)

Transcript

Add and Search Words. Design a dictionary that can add words and search for them. The twist: a search can contain dots, and a dot matches any one letter.

Say we add bat, bag and dad. Search pad: false. Dot A D: true, because the dot can be D, making dad. B A dot: true, it matches bat.

The simple way keeps a list and compares the pattern with every word. With thousands of words, each search scans them all, even words that start with the wrong letter.

Instead, hang the words as a trie. Each lantern holds one letter, and a word is a path down from the root. Bat and bag share their first two lanterns. A bell marks where a word ends, so D, A is a path, but not a word.

A letter in the pattern follows one string. A dot can be any letter, so it shines into every child, and depth-first search tries each branch. At a dead end, it backs up and tries the next, until it finds a bell.

In code, add walks down, creating missing children, then marks the end. Search recurses with a node and a position. At the pattern's end, return the mark. A dot tries every child and succeeds if any does. A letter follows its child, or fails if there's none.

Let's light it up. Pad: the root has no P, so false. Dot A D: the dot tries B first. B, A, but no D below, so it backs up. Next, D: D, A, D, and a bell. True. B A dot: B, A, then the dot tries T, and rings a bell. True.

Adding takes one step per letter, and so does a search without dots. But each dot can branch twenty-six ways, so with d dots, the worst case is twenty-six to the d, times the length. Space is at most one lantern per letter added.

Follow the letters, branch on the dots, back up at dead ends. That's Add and Search Words.