Skip to problem
←

Design Add and Search Words Data Structure

Medium 0 attempts

Design a data structure that lets you insert words one at a time and later check whether a given pattern matches any word you've stored, where a '.' in the pattern can stand in for any single character.

addWord(word) stores a lowercase word. search(pattern) checks the whole word, not just a prefix: each . matches exactly one lowercase letter. Inserting the same word again does not change which searches match.

Function contract

Implement class WordDictionary with a no-argument constructor. Each test creates one instance and applies the listed [method, word] calls in order.

Output: addWord(word) stores the word and returns nothing (displayed as null). search(pattern) returns true only when a stored whole word matches; each dot matches exactly one letter.

Example 1

Input
constructorArgs = []
operations = [["addWord","bad"],["addWord","dad"],["search","pad"],["search","bad"],["search",".ad"],["search","b.."]]
Output
[null,null,false,true,true,true]

Explanation: After storing bad and dad, .ad matches either word and b.. matches bad. pad is not stored.

Example 2

Input
constructorArgs = []
operations = [["search","a"],["addWord","ab"],["search","."],["search",".."]]
Output
[false,null,false,true]
Constraints
  • 1 <= word.length <= 25
  • addWord accepts lowercase letters only; search additionally accepts dot wildcards.
  • At most 10^4 calls.
Topics

Trie with DFS for Wildcards

javascript
class WordDictionary {
  constructor() {
    this.root = {};
  }
  addWord(word) {
    let node = this.root;
    for (const c of word) {
      if (!node[c]) node[c] = {};
      node = node[c];
    }
    node.$ = true;
  }
  search(word) {
    function dfs(node, i) {
      if (!node) return false;
      if (i === word.length) return !!node.$;
      if (word[i] === '.')
        return Object.keys(node).some((k) => k !== '$' && dfs(node[k], i + 1));
      return dfs(node[word[i]], i + 1);
    }
    return dfs(this.root, 0);
  }
}

Time: addWord O(L); search O(L) without wildcards and O(26^L) as a loose worst-case bound with wildcards, limited by the number of trie nodes visited. Space: O(total inserted characters) for the trie and O(L) recursion depth per search.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript