Design Add and Search Words Data Structure
Module 20 · Tries
Problem
Design a data structure supporting two methods:
addWord(word)— storeword.search(word)— returntrueif any stored word matchesword. Herewordmay contain the wildcard character., which matches any single letter.
Examples
Example 1
Input
addWord("bad"), addWord("dad"), addWord("mad"), search("pad")OutputfalseExample 2
Input
search("bad")OutputtrueExample 3
Input
search(".ad")OutputtrueExplanation. "." matches b, d, or m
Example 4
Input
search("b..")OutputtrueExplanation. b then any two letters matches "bad"
Constraints
stored words are lowercase
a–z, 1–25 characters; search patterns area–zor., 1–25 characters; up to 10⁴ calls.
Attempt it first
addWord is just the trie insert you already wrote — nothing changes
there. The whole problem lives in search, and specifically in the ..
Try it before reading on, and think hard about this: your trie's walk so
far has always been deterministic — at each character there was
exactly one edge to follow, or none. What does a . do to that? At a
., which child do you descend into?