TRT
Sign in
mediumAdvancedLeetCode#trie#wildcard search

Design add and search words

Store words in a trie and search patterns in which a dot matches any letter, branching only where the pattern has a dot.

The Runtime Theory Team1 min read
Taught inTriesPro — members onlyA trie stores strings as paths from a root, one character per edge, so words with a common prefix share nodes. Lookups and prefix queries cost time proportional to the query's length, however many words are stored.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inadd("bad"), add("dad"), add("mad"), search("pad"), search("bad"), search(".ad"), search("b..")

out[false, true, true, true]

inadd("a"), search("."), search("..")

out[true, false]

inadd("ab"), search("a."), search(".b."), search("..")

out[true, false, true]

Design a structure with addWord(word) and search(pattern), where the pattern may contain dots, and a dot matches any single letter. search returns whether any added word matches the whole pattern. The expected output lists the search results.

Before you code

On an ordinary letter, the walk follows one child. What must it do on a dot, and how does the trie keep that from exploding?

Hints

  1. Store the words in a trie with end-of-word flags.
  2. Search recursively with (node, index). On a letter, follow that child if it exists. On a dot, try every child.
  3. At the end of the pattern, return the node's end flag, not just whether the node exists.

Production & complexity notes

When solving Design add and search words on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Tries to reinforce the underlying pattern.

What it practices

Trie walks that branch, from Tries.

Not started

Sign in to save your learning progress.

Sign in to save