Magicsheet logo

Design Add and Search Words Data Structure

Medium
30%
Updated 6/1/2025

Design Add and Search Words Data Structure

1. What is this problem about?

The Design Add and Search Words Data Structure interview question requires implementing a dictionary that supports two operations: adding a new word and searching for a word. The "twist" is that the search query can contain the wildcard character '.', which matches any single letter. This Design Add and Search Words Data Structure coding problem is a step up from basic string matching.

2. Why is this asked in interviews?

Companies like Meta, Amazon, and Microsoft ask this to evaluate your mastery of the Trie (Prefix Tree) interview pattern. It tests your ability to adapt a standard data structure to handle fuzzy matching using recursion. It’s a perfect test of Depth-First Search (DFS) application on a tree-like structure.

3. Algorithmic pattern used

This problem is solved using a Trie with Recursive Backtracking.

  • Add Word: Standard Trie insertion. Each node contains a map or array of children and a boolean isEndOfWord.
  • Search Word:
    • If the current character is a letter, move to the corresponding child node.
    • If the character is '.', iterate through all existing children of the current node and recursively search the remainder of the word.
    • Return true if any of these recursive paths find a match.

4. Example explanation

Dictionary: ["bad", "dad", "mad"].

  1. search("pad"): Starts at root. No child 'p'. Returns false.
  2. search("bad"): Follows 'b' -> 'a' -> 'd'. isEndOfWord is true. Returns true.
  3. search(".ad"): At root, sees '.'.
    • Tries child 'b' -> "ad" matches? Yes.
    • Returns true.

5. Common mistakes candidates make

  • Inefficient Search: Trying to use a HashSet of all words. While add is fast, search with wildcards becomes O(extTotalWordsimesextWordLength)O( ext{Total Words} imes ext{Word Length}), which is too slow.
  • Infinite Recursion: Failing to correctly handle the base case where the end of the search string is reached.
  • Memory Management: Using a large array [26] for every node when the alphabet is sparse (though for 'a'-'z', an array is usually acceptable).

6. Interview preparation tip

Practice implementing a basic Trie from scratch before your interview. Once you're comfortable with insert and search, adding the wildcard logic is just a matter of adding a simple DFS loop for the '.' case.

Similar Questions