15% off all plans & roadmaps Use code

See plans

Design Add and Search Words Data Structure

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) stores word so later searches can match it.
  • bool search(word) returns true if some stored word matches word, and false otherwise. The query word may 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 True

Constraints

  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters.
  • word in search consists of '.' or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 10^4 calls will be made to addWord and search.

Constraints that matter

  • word.length <= 25 means 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 addWord and search means 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Create an empty list words in the constructor.
  2. In addWord, append the word to the list.
  3. In search, loop over every stored word.
  4. Skip a stored word if its length differs from the query length.
  5. Compare character by character. A query dot always matches; a letter must equal the stored letter.
  6. 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, return false.
  • addWord("a"): words = ["a"].
  • search("."): compare "a" with ".". The lengths are both 1. The query character is a dot, so it matches. Return true.
  • search("b"): compare "a" with "b". The letters differ, so there is no match. The list ends. Return false.

The outputs are [null, false, null, true, false].

Complexity

TimeaddWord O(L), search O(n * L)
SpaceO(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

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

  1. Create a map from length to a list of words.
  2. In addWord, append the word to the list stored under its length.
  3. In search, look up the bucket for the query length. If it does not exist, return false.
  4. For each word in the bucket, compare character by character, letting . match anything.
  5. Return true on the first full match.
  6. 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, return false.
  • addWord("a"): buckets = {1: ["a"]}.
  • search("."): the bucket for length 1 is ["a"]. The dot matches "a". Return true.
  • search("b"): the bucket for length 1 is ["a"]. "a" does not equal "b", so return false.

The outputs are [null, false, null, true, false].

Complexity

TimeaddWord O(L), search O(k * L)
SpaceO(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
Tries pattern infographic for Design Add and Search Words Data Structure

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

  1. Define a node with up to 26 children and a boolean end. Create one root node.
  2. In addWord, walk from the root, creating missing children for each letter, then set end = true on the last node.
  3. In search, call dfs(root, 0).
  4. In dfs, if the index equals the query length, return the node's end flag.
  5. If the current character is a letter, return false when that child is missing. Otherwise recurse into the child with index + 1.
  6. 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.
  7. 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.

StepOperationTrie stateWhat happensResult
1WordDictionary()root only, no childrenCreate the root node.null
2search("a")root has no childrendfs(root, 0): char a, root has no child a.false
3addWord("a")root -> a (end = true)Create node a, mark it as a word end.null
4search(".")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
5search("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

TimeaddWord O(L), search O(L) with no dots, at most O(26^2 * L) with two dots
SpaceO(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)

Common mistakes

  • Returning true when the index reaches the end of the query without checking node.end. The query "ba" would match the stored word "bad". Return node.end at that point, not true.
  • Marking the root or intermediate nodes as word ends, or forgetting node.end = true after 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 and search("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

Practise it