DSA Trie

Design Add and Search Words Data Structure

Trie with wildcard `.` search via DFS branching on unknown characters.

Medium
Time O(L) insert Space O(N * L)
LeetCode
5 min read
trie dfs design

Problem#

Design WordDictionary with:

  • addWord(word) — store a string.
  • search(word) — return true iff a stored word matches. word may contain . which matches any single letter.

Examples#

  • addWord("bad"); addWord("dad"); addWord("mad"); search("pad")false; search("bad")true; search(".ad")true; search("b..")true.

Constraints#

  • 1 <= word.length <= 25, up to 10^4 operations.

Hints#

Hint
On ., recurse into every existing child.

Approach#

Standard trie for insert. For search, recursive DFS: at each character either follow the deterministic child or, if the char is ., recurse into all 26 children. Backtrack on dead-ends.

Solution#

Design Add and Search Words Data Structure
class WordDictionary {
struct Node {
Node* child[26]{};
bool isEnd = false;
};
Node* root;
public:
WordDictionary() : root(new Node()) {}
void addWord(const string& word) {
Node* cur = root;
for (char c : word) {
int i = c - 'a';
if (!cur->child[i]) cur->child[i] = new Node();
cur = cur->child[i];
}
cur->isEnd = true;
}
bool search(const string& word) {
return dfs(root, word, 0);
}
private:
bool dfs(Node* node, const string& w, int idx) {
if (!node) return false;
if (idx == (int)w.size()) return node->isEnd;
char c = w[idx];
if (c == '.') {
for (int i = 0; i < 26; ++i) {
if (node->child[i] && dfs(node->child[i], w, idx + 1)) return true;
}
return false;
}
return dfs(node->child[c - 'a'], w, idx + 1);
}
};

Editorial#

Wildcards force branching, but only at dots — letters stay O(1). With k dots, worst-case work is 26^k paths multiplied by remaining depth. The trie still beats brute-force list scanning whenever stored words share prefixes.

Complexity#

  • Time: O(L) insert; O(26^k * L) worst-case search with k dots.
  • Space: O(N * L).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.