Sequential Word Dictionary With Exact and Prefix Lookups

Medium · Coding & Algorithms · Software Engineer · Other

Problem Statement

Implement an in-memory dictionary for lowercase English strings that executes a stream of commands sequentially. Every command in operations is a two-string pair [command, arg]:

  • ["insert", word]: stores word in the dictionary and emits no boolean output. Re-adding a string that was already stored leaves the dictionary unchanged.
  • ["search", word]: evaluates to True if word was previously stored as a complete entry, or False otherwise (matching only the beginning of a longer stored entry returns False).
  • ["prefix", pref]: evaluates to True if at least one previously stored entry begins with pref (an entry equal to pref counts as beginning with pref), or False otherwise.

The dictionary begins empty, and every lookup observes only entries added prior to that lookup. Return a list containing the boolean results of all "search" and "prefix" commands in their arrival order (or [] when the stream contains only insertions).

def run_word_index(operations: List[List[str]]) -> List[bool]:

Examples

Example 1

Input: operations = [
    ["insert", "planet"],
    ["prefix", "plan"],
    ["search", "plan"],
    ["insert", "plan"],
    ["search", "plan"],
    ["prefix", "plaza"]
]
Output: [True, False, True, False]

Explanation: After storing "planet", "plan" matches as a prefix (True) yet fails exact lookup (False) because "plan" itself has not been added yet. Once "plan" is inserted, exact lookup for "plan" becomes True, while "plaza" diverges at 'z' and returns False.

Example 2

Input: operations = [
    ["search", "go"],
    ["insert", "go"],
    ["insert", "go"],
    ["prefix", "go"],
    ["prefix", "goal"],
    ["search", "go"]
]
Output: [False, True, False, True]

Explanation: Looking up "go" before any insertion yields False. Storing "go" twice behaves identically to storing it once: "go" matches as a prefix of itself (True), "goal" extends past "go" (False), and exact lookup for "go" succeeds (True).

Example 3

Input: operations = [["insert", "mint"], ["insert", "mine"]]
Output: []

Explanation: Neither command is a lookup, so the returned result list is empty.

Constraints

  • 1 <= len(operations) <= 2 * 10^4
  • For each [command, arg], command is "insert", "search", or "prefix".
  • 1 <= len(arg) <= 100, consisting solely of lowercase ASCII letters ('a' through 'z').

Step-by-step walkthrough

  1. Understand the three operations

    We begin with an empty dictionary and replay a list of [op_name, text] commands sequentially (1 <= len(operations) <= 2 * 10^4, where text has 1..100 lowercase letters a..z):

    • ["insert", w]: record w in the dictionary (emits no boolean; re-inserting an existing word has no effect).
    • ["search", w]: return True only when w itself was previously stored as a whole word.
    • ["prefix", p]: return True whenever at least one previously stored word starts with p (including a stored word equal to p).

    Watch the distinction between "search" and "prefix":

    After only ["insert", "planet"]:
      ["prefix", "plan"]   ->  True    ("planet" begins with "plan")
      ["search", "plan"]   ->  False   ("plan" itself was not stored yet)
      ["prefix", "planet"] ->  True    ("planet" begins with "planet")
    
  2. Why scanning a plain word list is slow for prefixes

    If we store every inserted word in a Python set:

    • ["search", w] is w in words, which runs in O(len(w)) average time — already fast.
    • ["prefix", p], however, cannot use a single hash lookup on words: we would have to scan every stored word and check word.startswith(p).

    With 10,000 inserted words of length 100 followed by 10,000 prefix lookups, scanning every word per query performs up to 10,000 * 10,000 = 10^8 startswith checks. We want "prefix" to take only O(len(p)) steps, independent of how many words are stored!

  3. Key idea: share common beginnings in a tree of letters (a trie)

    A trie (also called a prefix tree) organizes words character by character from a shared root node. Words that begin with the same letters share the exact same chain of nodes before branching apart:

    After inserting "planet", "plan", and "play"  (* marks is_word = True):
    
              (root)
                |
               [p]
                |
               [l]
                |
               [a]
              /   \
           [n]*   [y]*
            |
           [e]
            |
           [t]*
    

    Look at what that structure gives us automatically:

    1. Every node was created while inserting some word. Therefore at least one stored word starts with p if and only if walking the letters of p from root never hits a missing link.
    2. A prefix node is not automatically a whole word. Before "plan" was inserted, [n] already existed along the path to [t]*, so we keep a boolean flag is_word on each node to mark where complete words finish.
  4. Build `TrieNode` and `insert`

    Each TrieNode stores two attributes:

    • children: a dictionary mapping a single letter (such as 'a') to the next TrieNode.
    • is_word: False initially, set to True on the node where an inserted word ends.

    To insert word, start at self.root, step through each letter (allocating a new TrieNode whenever a letter link is missing), and mark node.is_word = True at the final node. Inserting the same word twice walks the existing path and sets is_word = True again, so duplicates harmlessly do nothing.

    class TrieNode:
        def __init__(self) -> None:
            # children: maps single letter -> child TrieNode, e.g. {'a': TrieNode(), 'b': TrieNode()}.
            self.children: Dict[str, "TrieNode"] = {}
            # is_word: True only when at least one inserted word ends at this exact node.
            self.is_word: bool = False
    
    
    class Trie:
        def __init__(self) -> None:
            # The root represents the empty prefix "" before any letters are read.
            self.root = TrieNode()
    
        def insert(self, word: str) -> None:
            # Walk letter by letter from the root, creating missing child nodes as needed.
            node = self.root
            for letter in word:
                if letter not in node.children:
                    node.children[letter] = TrieNode()
                node = node.children[letter]
            # Mark the final letter's node as a complete word (duplicate inserts keep it True).
            node.is_word = True
    
  5. Share one read-only walk for `search` and `starts_with`

    Both "search" and "prefix" walk down from self.root letter by letter without modifying the tree. Let's place that shared traversal in a helper _find_node(text) that returns the reached TrieNode (or None as soon as a letter is missing):

    • search(word) returns True when node is not None and node.is_word.
    • starts_with(prefix) returns True when node is not None.

    Be careful never to create missing nodes inside _find_node (for instance with defaultdict): lookups must leave the trie completely unchanged!

        def _find_node(self, text: str) -> Optional[TrieNode]:
            """Follow `text` from the root without modifying the trie, or return None if broken."""
            node = self.root
            for letter in text:
                if letter not in node.children:
                    return None
                node = node.children[letter]
            return node
    
        def search(self, word: str) -> bool:
            # Exact match requires the full path to exist AND an inserted word to end here.
            node = self._find_node(word)
            return node is not None and node.is_word
    
        def starts_with(self, prefix: str) -> bool:
            # Every node in the trie was created along some inserted word, so path existence suffices.
            node = self._find_node(prefix)
            return node is not None
    
  6. Replay operations and trace Example 1

    Finally, run_word_index creates an empty Trie, iterates over operations in order, and appends boolean results only for "search" and "prefix".

    Let's trace Example 1:

    Operation               Trie state (* = is_word)               Walk result                  Output appended
    ---------------------   ------------------------------------   --------------------------   ---------------
    ["insert", "planet"]    root->p->l->a->n->e->t*                marks t.is_word = True       (none)
    ["prefix", "plan"]      root->p->l->a->n->e->t*                reaches n (not None)         True
    ["search", "plan"]      root->p->l->a->n->e->t*                reaches n, n.is_word=False   False
    ["insert", "plan"]      root->p->l->a->n*->e->t*               marks n.is_word = True       (none)
    ["search", "plan"]      root->p->l->a->n*->e->t*               reaches n*, n.is_word=True   True
    ["prefix", "plaza"]     root->p->l->a->n*->e->t*               a has no child 'z' -> None   False
    

    Collected answers: [True, False, True, False].

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TrieNode:
        def __init__(self) -> None:
            # children: maps single letter -> child TrieNode, e.g. {'a': TrieNode(), 'b': TrieNode()}.
            self.children: Dict[str, "TrieNode"] = {}
            # is_word: True only when at least one inserted word ends at this exact node.
            self.is_word: bool = False
    
    
    class Trie:
        def __init__(self) -> None:
            # The root represents the empty prefix "" before any letters are read.
            self.root = TrieNode()
    
        def insert(self, word: str) -> None:
            # Walk letter by letter from the root, creating missing child nodes as needed.
            node = self.root
            for letter in word:
                if letter not in node.children:
                    node.children[letter] = TrieNode()
                node = node.children[letter]
            # Mark the final letter's node as a complete word (duplicate inserts keep it True).
            node.is_word = True
    
        def _find_node(self, text: str) -> Optional[TrieNode]:
            """Follow `text` from the root without modifying the trie, or return None if broken."""
            node = self.root
            for letter in text:
                if letter not in node.children:
                    return None
                node = node.children[letter]
            return node
    
        def search(self, word: str) -> bool:
            # Exact match requires the full path to exist AND an inserted word to end here.
            node = self._find_node(word)
            return node is not None and node.is_word
    
        def starts_with(self, prefix: str) -> bool:
            # Every node in the trie was created along some inserted word, so path existence suffices.
            node = self._find_node(prefix)
            return node is not None
    
    
    def run_word_index(operations: List[List[str]]) -> List[bool]:
        trie = Trie()
        # answers: collects boolean results ONLY for "search" and "prefix" queries in order.
        answers: List[bool] = []
    
        for op_name, text in operations:
            if op_name == "insert":
                trie.insert(text)
            elif op_name == "search":
                answers.append(trie.search(text))
            elif op_name == "prefix":
                answers.append(trie.starts_with(text))
            else:
                raise ValueError(f"unknown operation: {op_name}")
    
        return answers
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine organizing words as a tree of road signs where each step follows a single letter from an entrance plaza (root). When you add "planet", you build a six-step path p -> l -> a -> n -> e -> t and stick a star (is_word = True) on t to mark that a complete word finishes there. Any word starting with "plan" — such as "plan", "planet", or "plank" — shares the exact same p -> l -> a -> n beginning! This structure is called a trie (or prefix tree, a tree where each edge is labeled with one character so shared word beginnings share nodes). Checking "prefix" just walks the letters and asks "did the road exist?", while checking "search" walks the same letters and also asks "does this signpost have a star?".

A naive implementation that keeps stored words in a hash set (an unordered collection supporting O(1) average exact-key lookup) handles "search" quickly, because exact lookup is what hash sets are built for. However, hash sets scramble keys by their full string hash, so answering ["prefix", p] forces you to scan every stored word and test word.startswith(p). With 10,000 inserts followed by 10,000 prefix queries, scanning every word takes up to 100 million startswith checks, whereas a trie walks at most len(p) <= 100 nodes per query regardless of how many words are stored.

Walk through Example 1 ([["insert", "planet"], ["prefix", "plan"], ["search", "plan"], ["insert", "plan"], ["search", "plan"], ["prefix", "plaza"]]):

  1. insert "planet": creates root -> p -> l -> a -> n -> e -> t and marks t.is_word = True (no output).
  2. prefix "plan": walks to n, sees n exists (not None), appends True.
  3. search "plan": walks to n, sees n.is_word is False, appends False.
  4. insert "plan": walks existing root -> p -> l -> a -> n and flips n.is_word = True (no output).
  5. search "plan": walks to n, sees n.is_word is now True, appends True.
  6. prefix "plaza": hits None at 'z' under 'a', appends False -> [True, False, True, False].

Complexity

Let L be the length of the word or prefix in a single operation (L <= 100), S be the sum of L across all operations (at most 2 * 10^4 * 100 = 2 * 10^6), and I be the total characters across all "insert" operations.

  • Time: O(L) per operation, and O(S) overall. Each "insert", "search", or "prefix" call steps through at most L characters, doing one O(1) average-time dictionary lookup (and at most one O(1) insertion during "insert") per character.
  • Space: O(I + Q), where Q is the number of queries. In the worst case where stored words share almost no prefixes, "insert" allocates at most one TrieNode per inserted character (O(I) nodes, often far fewer when prefixes overlap), and answers stores one boolean for each of the Q lookups.

Edge cases

  • Lookups on an empty dictionary: self.root.children is empty, so _find_node immediately returns None on the first character (L >= 1) and both "search" and "prefix" return False.
  • Prefix that is not yet a whole word: after insert "planet", search "plan" returns False while prefix "plan" returns True.
  • Prefix equal to a stored word: after insert "go", prefix "go" reaches o (not None) and returns True (Example 2).
  • Query longer than any stored word: after insert "go", prefix "goal" hits None at 'a' and returns False.
  • Duplicate inserts: inserting "go" twice walks the same path and leaves o.is_word = True unchanged.
  • Only "insert" operations: answers stays empty and returns [] (Example 3).
  • Separate branches with the same letters: inserting "ab" and "ba" creates independent paths root -> a -> b and root -> b -> a, never falsely matching "aa" or "bb".

Common mistakes

  • Omitting is_word: checking only whether the path exists makes search "plan" wrongly return True after inserting "planet".
  • Mutating the trie during lookups: using collections.defaultdict(TrieNode) and indexing node.children[letter] inside search or starts_with silently inserts phantom nodes, causing future "prefix" lookups on unstored strings to return True.
  • Defining children = {} as a class attribute instead of inside __init__: causes every TrieNode in the entire tree to share one single dictionary!
  • Appending None or True for "insert": the output list must contain answers only for "search" and "prefix" commands.
  • Scanning a list of all words on every "prefix" call: takes O(number of words * L) per lookup instead of O(L).

Alternative approaches

  • Two hash sets (words and prefixes): on insert(w), add w to words and add every slice w[:1], w[:2], ..., w[:L] to prefixes, turning both "search" and "prefix" into O(L) hash lookups. However, slicing and hashing every prefix takes O(L^2) character copies per insert (about 5,050 characters per 100-letter word) instead of O(L), and does not naturally extend to autocomplete or deletion.
  • Sorted word list with binary search (bisect_left): keep distinct inserted words in alphabetical order; some word starts with p if and only if the first stored word >= p (found in O(log N) comparisons via binary search, repeatedly halving the sorted list) starts with p. Queries are fast, but inserting into the middle of a Python list shifts elements in O(N) time per insert.

Follow-up questions

  • How would you extend the trie to report how many distinct stored words begin with a given prefix? Add an integer prefix_count = 0 to every TrieNode. Before inserting word, check if self.search(word): return so duplicate inserts are ignored; otherwise walk from root through word and increment node.prefix_count += 1 at every node along the path. Answering a prefix-count lookup then runs _find_node(p) in O(len(p)) time and returns node.prefix_count (or 0 when node is None).
  • How would you implement word deletion without leaving stale paths that break future prefix checks? First confirm w is stored in the trie; if so, clear end_node.is_word = False at the end of w's path. You must also prune dead branches on the way back up—deleting any child node whose is_word is False and whose children dict is now empty—otherwise starts_with would still see leftover nodes from the deleted word and return True. Alternatively, maintain prefix_count on every node, decrement it along w's path on deletion, and treat any node with prefix_count == 0 as absent.
  • How would you return the top k autocomplete suggestions for a typed prefix? Call _find_node(p) to jump directly to p's subtree in O(len(p)) time; if None, return []. To return the k alphabetically smallest completions, run a depth-first search (exploring one letter branch to its end before backtracking to the next) from that node visiting child letters from 'a' to 'z' and stop as soon as you collect k nodes with is_word == True. If completions are ranked by popularity instead, precompute and cache each node's top-k highest-scoring words during insert so queries return in O(len(p) + k) time without traversing the full subtree.

Follow-up questions

Similar questions

More Nielsen interview questions

All 5 Nielsen questions →