InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Tries

Design Add and Search Words Data Structure

medium Original ↗ 00:00

Problem

Design a container for lowercase words that supports:

  • WordDictionary() — create an empty container.
  • addWord(word) — store word.
  • search(word) — return True if any stored word matches word, where word may contain the wildcard character '.'. A '.' matches exactly one arbitrary letter; every other character must match literally. The match must cover the whole word (same length).

So after adding "bad", the query "b.d" matches, ".ad" matches, but "b." does not (wrong length) and "b.dx" does not.

Examples

  • addWord("bad"), addWord("dad"), addWord("mad"); then search("pad")False — no stored word is "pad".
  • search("bad")True (exact match); search(".ad")True — the dot can stand for b, d, or m.
  • search("b..")True"bad" matches with . standing for a then d; search("..")False — all stored words have length 3.

Constraints

  • 1 <= len(word) <= 25 for both added and searched words.
  • Added words contain only lowercase letters; search queries contain lowercase letters and '.'.
  • There are at most 2 '.' characters in any single search query.
  • At most 10^4 calls total to addWord and search.

Think about it first

Hint 1 Without dots, this is the standard trie problem. Consider what changes when a '.' appears in the middle of the walk.
Hint 2 A '.' does not identify which child edge to follow, so follow all of them. The single-path walk becomes a branching search.
Hint 3 Write a recursive matcher dfs(node, i): if word[i] is a letter, descend into that one child; if it is '.', try every child and succeed if any branch does. At i == len(word), succeed iff node.is_end.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug