15% off all plans & roadmaps Use code
See plansDesign Add and Search Words Data Structure
- LeetCode 211
- Medium
- Design Patterns
- Tries
Updated
TL;DR: Build a dictionary that stores words and answers queries where '.' matches any letter. Store words in a Trie, and when a query hits '.', branch into every child with a DFS.
Problem
Design a data structure that lets you add words and check whether a query string matches any word added earlier.
Implement the WordDictionary class:
WordDictionary()creates an empty dictionary.void addWord(word)storeswordso later searches can match it.bool search(word)returnstrueif some stored word matchesword, andfalseotherwise. The querywordmay contain dots'.', and each dot matches any single letter.
Example 1
Input: ["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output: [null,null,null,null,false,true,true,true]
Explanation:
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return TrueConstraints
1 <= word.length <= 25wordinaddWordconsists of lowercase English letters.wordinsearchconsists of'.'or lowercase English letters.- There will be at most
2dots inwordforsearchqueries. - At most
10^4calls will be made toaddWordandsearch.
Constraints that matter
word.length <= 25means every recursion or comparison loop is short, so the depth of any DFS is at most 25.- At most 2 dots per query caps the branching. A DFS fans out at most 26 * 26 times before every remaining character is a literal, so a Trie search stays cheap.
- Up to 10^4 calls to
addWordandsearchmeans a list scan costing O(n * L) per search can reach about 10^4 * 10^4 * 25 character checks in the worst case. That is too slow to rely on. - Lowercase letters only means each Trie node needs at most 26 children, so a fixed array of 26 works.
- Dots only appear in queries, never in stored words, so insertion is plain Trie insertion.
Hints
Hint 1
The pattern is a Trie (prefix tree) with a DFS for the wildcard.
Hint 2
Keep all added words in a plain list.
Solution
Intuition
The pattern is a Trie (prefix tree) with a DFS for the wildcard. Words that share a prefix share the same path of nodes, so you never compare the same prefix twice. A plain letter in the query moves you to exactly one child. A dot moves you into every child.
Picture a filing cabinet where each drawer is labeled with one letter and drawers nest inside drawers, so every word is a path of folders ending in a marked folder. A dot in the query is like telling someone to check every drawer at that level, while a plain letter means open only one drawer.
The clue is the dot. Exact matching would be a hash set lookup, but a dot breaks hashing because you do not know the letter and cannot compute the key. You need a structure that lets you walk the word one character at a time and branch at a chosen position. That is what a Trie gives you.
Every stored word is a path from the root to a node flagged as a word end. A query matches a stored word exactly when some path from the root spells it, with each dot standing for any edge. The DFS tries every edge at a dot and one edge at a letter. If any branch reaches the end of the query on a flagged node, you return true.
The at-most-2-dots rule keeps the branching small. Without it, a query of 25 dots would visit every node in the tree. With it, at most 26 * 26 branches ever split, and each continues along at most 25 literal steps.
Worked example
Input: Operations: ["WordDictionary", "search", "addWord", "search", "search"]
Arguments: [[], ["a"], ["a"], ["."], ["b"]]
Output: [null, false, null, true, false]
Explanation: The dictionary starts empty, so searching "a" fails. After addWord("a"), the query "." matches it because a dot accepts any single letter. The query "b" has no matching stored word, so it returns false.Approach 1: Brute force
Keep all added words in a plain list. On search, compare the query against every stored word, one character at a time, treating . as a match for anything.
This is correct and takes a few lines. It needs no insight beyond the definition of a match.
Steps
- Create an empty list
wordsin the constructor. - In
addWord, append the word to the list. - In
search, loop over every stored word. - Skip a stored word if its length differs from the query length.
- Compare character by character. A query dot always matches; a letter must equal the stored letter.
- Return true on the first stored word with no mismatch. Return false after the loop ends.
Dry run
Trace of the example, with words as the list.
- Start:
words = []. search("a"): the list is empty, the loop never runs, returnfalse.addWord("a"):words = ["a"].search("."): compare "a" with ".". The lengths are both 1. The query character is a dot, so it matches. Returntrue.search("b"): compare "a" with "b". The letters differ, so there is no match. The list ends. Returnfalse.
The outputs are [null, false, null, true, false].
Complexity
| Time | addWord O(L), search O(n * L) |
|---|---|
| Space | O(n * L) |
Let n be the number of stored words and L the word length (at most 25). addWord appends one string, which costs O(L) to store it. search visits all n stored words and compares up to L characters in each, so it is O(n * L). The list holds n strings of up to L characters, so space is O(n * L).
PythonTested in our runner
from typing import List, Optional
class WordDictionary:
def __init__(self):
self.words = []
def addWord(self, word: str) -> None:
self.words.append(word)
def search(self, word: str) -> bool:
for stored in self.words:
if len(stored) != len(word):
continue
ok = True
for a, b in zip(stored, word):
if b != '.' and a != b:
ok = False
break
if ok:
return True
return False
JavaTested in our runner
import java.util.*;
class WordDictionary {
private final List<String> words = new ArrayList<>();
public WordDictionary() {
}
public void addWord(String word) {
words.add(word);
}
public boolean search(String word) {
for (String stored : words) {
if (stored.length() != word.length()) {
continue;
}
boolean ok = true;
for (int i = 0; i < word.length(); i++) {
char q = word.charAt(i);
if (q != '.' && q != stored.charAt(i)) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
}
}
C++Tested in our runner
#include <string>
#include <vector>
using namespace std;
class WordDictionary {
private:
vector<string> words;
public:
WordDictionary() {
}
void addWord(string word) {
words.push_back(word);
}
bool search(string word) {
for (const string& stored : words) {
if (stored.size() != word.size()) {
continue;
}
bool ok = true;
for (size_t i = 0; i < word.size(); i++) {
if (word[i] != '.' && word[i] != stored[i]) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
}
};
JavaScriptTested in our runner
var WordDictionary = function() {
this.words = [];
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
this.words.push(word);
};
/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
for (const stored of this.words) {
if (stored.length !== word.length) {
continue;
}
let ok = true;
for (let i = 0; i < word.length; i++) {
if (word[i] !== '.' && word[i] !== stored[i]) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
};
GoTested in our runner
type WordDictionary struct {
words []string
}
func Constructor() WordDictionary {
return WordDictionary{}
}
func (this *WordDictionary) addWord(word string) {
this.words = append(this.words, word)
}
func (this *WordDictionary) search(word string) bool {
for _, stored := range this.words {
if len(stored) != len(word) {
continue
}
ok := true
for i := 0; i < len(word); i++ {
if word[i] != '.' && word[i] != stored[i] {
ok = false
break
}
}
if ok {
return true
}
}
return false
}
C#Tested in our runner
public class WordDictionary {
private readonly List<string> words = new List<string>();
public WordDictionary() {
}
public void addWord(string word) {
words.Add(word);
}
public bool search(string word) {
foreach (string stored in words) {
if (stored.Length != word.Length) {
continue;
}
bool ok = true;
for (int i = 0; i < word.Length; i++) {
if (word[i] != '.' && word[i] != stored[i]) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
}
}
Approach 2: Bucket words by length
What's slow: the list scan compares the query against every stored word, even words of the wrong length. Those can never match, yet you still touch each one.
The insight that fixes it: a match needs equal lengths, so store words in buckets keyed by length. A search then scans only the bucket for the query's length. This removes the wasted length checks. You still compare against every word in that bucket, and words sharing a prefix are still compared again and again.
Steps
- Create a map from length to a list of words.
- In
addWord, append the word to the list stored under its length. - In
search, look up the bucket for the query length. If it does not exist, return false. - For each word in the bucket, compare character by character, letting
.match anything. - Return true on the first full match.
- Return false when the bucket is exhausted.
Dry run
Trace of the example, with buckets as the map.
- Start:
buckets = {}. search("a"): no bucket for length 1, returnfalse.addWord("a"):buckets = {1: ["a"]}.search("."): the bucket for length 1 is["a"]. The dot matches "a". Returntrue.search("b"): the bucket for length 1 is["a"]. "a" does not equal "b", so returnfalse.
The outputs are [null, false, null, true, false].
Complexity
| Time | addWord O(L), search O(k * L) |
|---|---|
| Space | O(n * L) |
Let n be the number of stored words, L the word length, and k the number of stored words with the query's length, where k <= n. addWord does one map insert and one append, which is O(L) including the string copy. search compares at most k words of up to L characters, so it is O(k * L). In the worst case all words share one length, so k = n and the bound matches the brute force. Space is the same n strings of up to L characters.
PythonTested in our runner
from typing import List, Optional
class WordDictionary:
def __init__(self):
self.buckets = {}
def addWord(self, word: str) -> None:
self.buckets.setdefault(len(word), []).append(word)
def search(self, word: str) -> bool:
for stored in self.buckets.get(len(word), []):
ok = True
for a, b in zip(stored, word):
if b != '.' and a != b:
ok = False
break
if ok:
return True
return False
JavaTested in our runner
import java.util.*;
class WordDictionary {
private final Map<Integer, List<String>> buckets = new HashMap<>();
public WordDictionary() {
}
public void addWord(String word) {
buckets.computeIfAbsent(word.length(), k -> new ArrayList<>()).add(word);
}
public boolean search(String word) {
List<String> bucket = buckets.get(word.length());
if (bucket == null) {
return false;
}
for (String stored : bucket) {
boolean ok = true;
for (int i = 0; i < word.length(); i++) {
char q = word.charAt(i);
if (q != '.' && q != stored.charAt(i)) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
}
}
C++Tested in our runner
#include <string>
#include <vector>
#include <unordered_map>
using namespace std;
class WordDictionary {
private:
unordered_map<int, vector<string>> buckets;
public:
WordDictionary() {
}
void addWord(string word) {
buckets[(int)word.size()].push_back(word);
}
bool search(string word) {
auto it = buckets.find((int)word.size());
if (it == buckets.end()) {
return false;
}
for (const string& stored : it->second) {
bool ok = true;
for (size_t i = 0; i < word.size(); i++) {
if (word[i] != '.' && word[i] != stored[i]) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
}
};
JavaScriptTested in our runner
var WordDictionary = function() {
this.buckets = new Map();
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
if (!this.buckets.has(word.length)) {
this.buckets.set(word.length, []);
}
this.buckets.get(word.length).push(word);
};
/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
const bucket = this.buckets.get(word.length);
if (!bucket) {
return false;
}
for (const stored of bucket) {
let ok = true;
for (let i = 0; i < word.length; i++) {
if (word[i] !== '.' && word[i] !== stored[i]) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
};
GoTested in our runner
type WordDictionary struct {
buckets map[int][]string
}
func Constructor() WordDictionary {
return WordDictionary{buckets: make(map[int][]string)}
}
func (this *WordDictionary) addWord(word string) {
this.buckets[len(word)] = append(this.buckets[len(word)], word)
}
func (this *WordDictionary) search(word string) bool {
for _, stored := range this.buckets[len(word)] {
ok := true
for i := 0; i < len(word); i++ {
if word[i] != '.' && word[i] != stored[i] {
ok = false
break
}
}
if ok {
return true
}
}
return false
}
C#Tested in our runner
public class WordDictionary {
private readonly Dictionary<int, List<string>> buckets = new Dictionary<int, List<string>>();
public WordDictionary() {
}
public void addWord(string word) {
if (!buckets.ContainsKey(word.Length)) {
buckets[word.Length] = new List<string>();
}
buckets[word.Length].Add(word);
}
public bool search(string word) {
if (!buckets.TryGetValue(word.Length, out List<string> bucket)) {
return false;
}
foreach (string stored in bucket) {
bool ok = true;
for (int i = 0; i < word.Length; i++) {
if (word[i] != '.' && word[i] != stored[i]) {
ok = false;
break;
}
}
if (ok) {
return true;
}
}
return false;
}
}

Solution pattern
Tries
Part of Design Patterns
Approach 3: Trie with DFS on dotsOptimalTries
What's slow: even with length buckets, you compare the query against whole words one by one. Words like "bad", "bat" and "ban" repeat the same work on "ba". A query with a literal first letter still scans words that start with other letters.
The insight that fixes it: store words in a Trie so that shared prefixes share nodes. A literal letter follows one edge and discards every word that does not start with it. A dot is the only place you branch, and the constraints allow at most two of them. Each node has up to 26 children and an end flag that marks where a stored word stops.
The search is a recursive DFS dfs(node, i), where i is the index of the next query character. If i equals the query length, return node.end. If the character is a letter, go to that child or return false. If it is a dot, try every existing child and return true if any succeeds.
Why it is correct. The trie holds every stored word as exactly one root-to-node path, and a node is marked end only where a word stops. A literal letter follows the single edge that matches, so no stored word with that letter is skipped. A dot tries every existing child, so any word that fits the pattern is reached on some branch. Returning true on the first success is safe because one matching path is enough to answer the query.
Steps
- Define a node with up to 26 children and a boolean
end. Create one root node. - In
addWord, walk from the root, creating missing children for each letter, then setend = trueon the last node. - In
search, calldfs(root, 0). - In
dfs, if the index equals the query length, return the node'sendflag. - If the current character is a letter, return false when that child is missing. Otherwise recurse into the child with index + 1.
- If the current character is a dot, loop over every existing child and recurse with index + 1. Return true as soon as one call returns true.
- Return false if no child succeeds.
Dry run
Trace of the example. Each node is named by the path from the root, so the root is "", and "a" is the child reached by letter a.
| Step | Operation | Trie state | What happens | Result |
|---|---|---|---|---|
| 1 | WordDictionary() | root only, no children | Create the root node. | null |
| 2 | search("a") | root has no children | dfs(root, 0): char a, root has no child a. | false |
| 3 | addWord("a") | root -> a (end = true) | Create node a, mark it as a word end. | null |
| 4 | search(".") | root -> a (end) | dfs(root, 0): char is a dot, try child a. dfs(a, 1): index 1 equals length 1, return a.end = true. | true |
| 5 | search("b") | root -> a (end) | dfs(root, 0): char b, root has no child b. | false |
The outputs are [null, false, null, true, false].
On the statement's example, search("b..") follows b, then the dot tries child a, then the second dot tries child d. Index 3 equals the length and node bad has end = true, so it returns true.
Complexity
| Time | addWord O(L), search O(L) with no dots, at most O(26^2 * L) with two dots |
|---|---|
| Space | O(T * 26) with array children, where T is the total characters stored |
Let L be the word length (at most 25) and T the total number of characters across all added words. addWord creates at most one node per character, so it is O(L). A query with no dots follows a single path of at most L nodes. Each dot fans out into at most 26 children, so two dots create at most 26 * 26 = 676 paths, each at most L steps long, which gives O(26^2 * L).
The Trie has at most T nodes, each holding an array of 26 child slots, so space is O(T * 26). Recursion depth is at most L.
PythonTested in our runner
from typing import List, Optional
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class WordDictionary:
def __init__(self):
self.root = TrieNode()
def addWord(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
def search(self, word: str) -> bool:
def dfs(node, i):
if i == len(word):
return node.is_end
ch = word[i]
if ch == '.':
# A dot tries every existing child.
for child in node.children.values():
if dfs(child, i + 1):
return True
return False
nxt = node.children.get(ch)
return nxt is not None and dfs(nxt, i + 1)
return dfs(self.root, 0)
JavaTested in our runner
import java.util.*;
class WordDictionary {
private static class Node {
Node[] next = new Node[26];
boolean end;
}
private final Node root = new Node();
public WordDictionary() {
}
public void addWord(String word) {
Node node = root;
for (int i = 0; i < word.length(); i++) {
int c = word.charAt(i) - 'a';
if (node.next[c] == null) {
node.next[c] = new Node();
}
node = node.next[c];
}
node.end = true;
}
public boolean search(String word) {
return dfs(root, word, 0);
}
private boolean dfs(Node node, String word, int i) {
if (i == word.length()) {
return node.end;
}
char ch = word.charAt(i);
if (ch == '.') {
// A dot tries every existing child.
for (Node child : node.next) {
if (child != null && dfs(child, word, i + 1)) {
return true;
}
}
return false;
}
Node child = node.next[ch - 'a'];
return child != null && dfs(child, word, i + 1);
}
}
C++Tested in our runner
#include <string>
using namespace std;
class WordDictionary {
private:
struct Node {
Node* next[26] = {};
bool end = false;
};
Node* root;
bool dfs(Node* node, const string& word, int i) {
if (i == (int)word.size()) {
return node->end;
}
char ch = word[i];
if (ch == '.') {
// A dot tries every existing child.
for (int c = 0; c < 26; c++) {
if (node->next[c] != nullptr && dfs(node->next[c], word, i + 1)) {
return true;
}
}
return false;
}
Node* child = node->next[ch - 'a'];
return child != nullptr && dfs(child, word, i + 1);
}
public:
WordDictionary() {
root = new Node();
}
void addWord(string word) {
Node* node = root;
for (char ch : word) {
int c = ch - 'a';
if (node->next[c] == nullptr) {
node->next[c] = new Node();
}
node = node->next[c];
}
node->end = true;
}
bool search(string word) {
return dfs(root, word, 0);
}
};
JavaScriptTested in our runner
class TrieNode {
constructor() {
this.children = new Map();
this.end = false;
}
}
var WordDictionary = function() {
this.root = new TrieNode();
};
/**
* @param {string} word
* @return {void}
*/
WordDictionary.prototype.addWord = function(word) {
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) {
node.children.set(ch, new TrieNode());
}
node = node.children.get(ch);
}
node.end = true;
};
/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
const dfs = (node, i) => {
if (i === word.length) {
return node.end;
}
const ch = word[i];
if (ch === '.') {
// A dot tries every existing child.
for (const child of node.children.values()) {
if (dfs(child, i + 1)) {
return true;
}
}
return false;
}
const next = node.children.get(ch);
return next !== undefined && dfs(next, i + 1);
};
return dfs(this.root, 0);
};
GoTested in our runner
type trieNode struct {
next [26]*trieNode
end bool
}
type WordDictionary struct {
root *trieNode
}
func Constructor() WordDictionary {
return WordDictionary{root: &trieNode{}}
}
func (this *WordDictionary) addWord(word string) {
node := this.root
for i := 0; i < len(word); i++ {
c := word[i] - 'a'
if node.next[c] == nil {
node.next[c] = &trieNode{}
}
node = node.next[c]
}
node.end = true
}
func (this *WordDictionary) search(word string) bool {
return dfsTrie(this.root, word, 0)
}
func dfsTrie(node *trieNode, word string, i int) bool {
if i == len(word) {
return node.end
}
ch := word[i]
if ch == '.' {
// A dot tries every existing child.
for c := 0; c < 26; c++ {
if node.next[c] != nil && dfsTrie(node.next[c], word, i+1) {
return true
}
}
return false
}
child := node.next[ch-'a']
return child != nil && dfsTrie(child, word, i+1)
}
C#Tested in our runner
public class WordDictionary {
private class Node {
public Node[] Next = new Node[26];
public bool End;
}
private readonly Node root = new Node();
public WordDictionary() {
}
public void addWord(string word) {
Node node = root;
foreach (char ch in word) {
int c = ch - 'a';
if (node.Next[c] == null) {
node.Next[c] = new Node();
}
node = node.Next[c];
}
node.End = true;
}
public bool search(string word) {
return Dfs(root, word, 0);
}
private bool Dfs(Node node, string word, int i) {
if (i == word.Length) {
return node.End;
}
char ch = word[i];
if (ch == '.') {
// A dot tries every existing child.
foreach (Node child in node.Next) {
if (child != null && Dfs(child, word, i + 1)) {
return true;
}
}
return false;
}
Node nxt = node.Next[ch - 'a'];
return nxt != null && Dfs(nxt, word, i + 1);
}
}
Common mistakes
- Returning
truewhen the index reaches the end of the query without checkingnode.end. The query "ba" would match the stored word "bad". Returnnode.endat that point, nottrue. - Marking the root or intermediate nodes as word ends, or forgetting
node.end = trueafter the insert loop. Set the flag only on the last node of each added word. - Handling a dot by following one arbitrary child. A dot must try every child, and the search succeeds if any branch succeeds. Loop over all children and return true on the first success.
- Returning the result of the first child in the dot loop, for example
return dfs(child, i + 1)inside the loop. That stops after one child. Only return early on true, and return false after the loop. - Indexing
children['.' - 'a']in the array version. The dot has no slot, so it throws or reads garbage. Check for'.'before computing the child index. - Comparing the query against stored words of any length in the scan approach. "b." must not match "bad". Check that the lengths are equal, or compare all characters through the end of both strings.
Edge cases
- Search before any word is added, such as
search("a")on an empty dictionary: return false. - A query that is a strict prefix of a stored word, such as stored "bad" and query "ba": return false because the node for "ba" is not a word end.
- A query longer than every stored word, such as stored "bad" and query "bad.": return false because the path ends before the dot is consumed.
- All-dot query matching the right length, such as "..." with stored "bad": return true. With stored "bad" and query "..", return false.
- Duplicate adds, such as adding "bad" twice: the second insert reuses the same nodes and sets the same flag, so searches behave the same and no extra memory is used.
- Single-letter words with a dot, as in the page example: after
addWord("a"),search(".")returns true andsearch("b")returns false.
Follow-ups interviewers ask
- What if queries could contain many dots, even all of them?
- The Trie DFS can then visit every node, so a query is O(T) in the worst case, where T is the number of nodes. To cut that down, keep a Trie per word length, so a dot-heavy query only explores words of the right length. You can also prune early by storing the maximum remaining depth on each node and skipping a branch that is too shallow.
- How would you reduce memory for the Trie?
- Replace the 26-slot array with a hash map from letter to child, so each node only pays for the children it has. That helps when the dictionary is sparse. A compressed Trie (radix tree) merges chains of single-child nodes into one edge. It cuts node count further, at the cost of more complex insertion.
- How would you also support deleting a word?
- Walk to the word's last node and set
end = false. Then, on the way back up, remove any node that has no children and is not a word end. That keeps the Trie free of dead branches. Deletion costs O(L) for a word of length L.
Design Add and Search Words Data Structure FAQ
What is the time complexity of Design Add and Search Words Data Structure?
With a Trie, addWord is O(L) for a word of length L. search is O(L) when the query has no dots, and at most O(26^2 * L) with the two dots the constraints allow. The list-scan approach costs O(n * L) per search, where n is the number of stored words.
Why use a Trie for Design Add and Search Words Data Structure?
Words that share a prefix share the same nodes, so a literal letter discards every word that does not start with it in one step. A hash set cannot handle a dot because you do not know the letter to hash. A Trie lets you walk one position at a time and branch only where the query has a dot.
Can Design Add and Search Words Data Structure be solved in O(1) extra space?
Not in a useful way. The structure must store all added words, so total space is at least proportional to the input. During a search, the Trie DFS uses O(L) stack space for the recursion, which is at most 25 frames here. You can write the search with an explicit stack, but the depth bound is the same.
How do I handle the dot wildcard in LeetCode 211?
When the current query character is a dot, loop over every existing child of the current node. Recurse into each with the next index, and return true if any call returns true. When the character is a letter, go to that one child, or return false if it does not exist.
Do I need an end-of-word flag in the Trie?
Yes. A node on the path to "bad" also represents "b" and "ba", but those were never added. The end flag marks which nodes complete a stored word. Without it, every prefix of a stored word would match.
Should the Trie children be an array or a hash map?
Both work. A 26-slot array gives fast direct indexing and suits lowercase-only input. A hash map saves memory on sparse nodes and makes the dot loop skip missing letters automatically. The dot loop on an array must check for null children.
Asked at
See which companies ask this — Pro
Related problems
- Implement Trie (Prefix Tree) · same technique: Tries
- Extra Characters in a String · same technique: Tries
- Replace Words · same technique: Tries
- Design Search Autocomplete System · same technique: Tries
- Word Squares · same technique: Tries
- LRU Cache · same pattern: Design Patterns
- Min Stack · same pattern: Design Patterns
- Time Based Key-Value Store · same pattern: Design Patterns
- Encode and Decode Strings · same pattern: Design Patterns
- Detect Squares · same pattern: Design Patterns