Design Add and Search Words Data Structure
Problem
Build a structure that stores lowercase words and answers pattern queries. It supports:
addWord(word): storeword.search(pattern): returnTrueif some stored word matchespattern, where each.in the pattern matches exactly one arbitrary letter and every other character must match literally. The lengths must be equal.Words and patterns are each at most a few dozen characters long.
Words contain only
a–z; patterns containa–zand..Expect up to several thousand
searchcalls, most patterns holding only one or two dots (the solution must still be correct if a pattern is nothing but dots).
Examples
addWord("fox"),addWord("box"),addWord("fix");search("cox")→False(no word starts withc);search("fox")→True;search(".ox")→Truebecause the dot can stand forforb;search("f.x")→True.addWord("go");search(".")→Falsebecause lengths differ;search("..")→True.addWord("tree");search("tre")→False: a prefix is not a match, only a full word is.
Hints
- Without dots, this is exactly a trie with
insertandsearch. - When you meet a
., you cannot pick a single child. What do you have to do with all of them? - Recursive DFS over the trie: on a letter follow one child, on a dot try every child, and succeed only if some branch reaches a terminal node at exactly the last character.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.