#211

Design Add and Search Words Data Structure

Medium Trie + DFS for wildcards

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Support addWord(word) and search(pattern), where '.' in the pattern matches any one letter.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: search where '.' matches any letter.

Why this works: same trie; on '.', try every child (a small DFS).

Example: add "bad", "dad"

search ".ad" → try b, d, … → "bad" ✓ → true

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Storing words in a list and regex-matching each one on every search.

Solve on LeetCode ↗
Complexity
  • Time: O(L) to add; search is O(L) without dots, up to O(26^d · L) with d dots.
  • Space: O(total characters).
Topic: Trie
🎬 Episode 97: video coming soon