Design Add and Search Words Data Structure

Medium

Topics
TrieDesignDFSString

Design a data structure with addWord(word) and search(word). In search, a . can match any single letter. search returns whether any added word matches.

Example 1

returnsWordDictionary()addWord(bad)addWord(dad)addWord(mad)search(pad)falsesearch(bad)truesearch(.ad)truesearch(b..)true
Two operations: store a word, and ask whether a pattern matches one that was stored. A . in the pattern stands for exactly one character, never a run of them, so a pattern only ever matches a stored word of the same length.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["WordDictionary","addWord","addWord","addWord","search","search","search","search"], values = [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output: [null,null,null,null,false,true,true,true]

Constraints

  • 1 <= word.length <= 25
  • Added words are lowercase letters; search words may contain ".".
  • At most 10^4 calls.
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is a trie plus wildcard search. On a normal character you descend one child; on a . you must try every child (a DFS branch).

Approach

  1. Store words in a trie keyed by length and characters.
  2. addWord inserts normally.
  3. search walks the trie; at a "." it recurses into all children, succeeding if any branch reaches an end node.

Dry Run

addWord bad, dad, mad. The root now has three children: b, d, m.
  search pad   -> false   no p child at the root, so it fails on the first letter
  search bad   -> true    an ordinary walk
  search .ad   -> true    the dot forks: try b, then d, then m
                          b -> a -> d, end set   ->  true, and the rest is skipped
  search b..   -> true    b, then dot over its only child a, then dot over d
answer null|null|null|null|false|true|true|true
The dot has to BRANCH, not advance. It tries every child of the current node and
succeeds if any subtree matches the remaining pattern, which is why search is
recursive while addWord is a plain loop.
Treat a dot as "skip this position" instead -- recursing on the same node with
i + 1 -- and both .ad and b.. return false. The pattern length stops lining up
with the depth reached, so nothing with a dot in it can ever match.
`any(...)` short-circuits, so .ad stops at the b branch here. The worst case is
still every node at that depth, which is where the 26^d factor in the complexity
comes from -- a pattern of all dots explores the whole trie to that depth.

Complexity

  • Time — O(26^d * L): wildcards can branch across 26 children at each dotted position.
  • Space — O(total chars): the trie nodes.

Common Pitfalls

  • A "." must try every child, not just skip a position.

Full Solution — all languages

class WordDictionary:
    def __init__(self):
        self.ch = {}
        self.end = False
    def addWord(self, word):
        node = self
        for c in word:
            node = node.ch.setdefault(c, WordDictionary())
        node.end = True
    def search(self, word):
        def dfs(node, i):
            if i == len(word):
                return node.end
            c = word[i]
            if c == ".":
                return any(dfs(x, i + 1) for x in node.ch.values())
            return c in node.ch and dfs(node.ch[c], i + 1)
        return dfs(self, 0)
Asked at Atlassian Snowflake
SensAI
Beta
Tap the mic to stop voice mode