InterviewPrepKit

Home / Coding / Tries

Implement Trie (Prefix Tree)

medium Original β†—
Solving tips
  • Build a tree of nodes each holding a children map (letter to node) plus an is_end boolean; words sharing a prefix share storage.
  • insert walks the path creating missing nodes and sets is_end on the last; search and startsWith both walk the path, differing only in the final is_end check.
  • Crucial distinction: search must also verify is_end, else 'app' wrongly matches after only 'apple' was inserted.
  • Every operation is O(L) in the word/prefix length, independent of how many words are stored; space is O(total characters inserted).

Problem

Build a data structure that stores a collection of lowercase strings and supports three operations:

  • Trie() β€” create an empty structure.
  • insert(word) β€” add word to the structure.
  • search(word) β€” return True if word was previously inserted as a complete word, False otherwise.
  • startsWith(prefix) β€” return True if any previously inserted word begins with prefix, False otherwise.

The distinction between search and startsWith matters: after inserting "apple", search("app") is False but startsWith("app") is True.

Examples

  • insert("apple"), then search("apple") β†’ True β€” the exact word was inserted.
  • After the above, search("app") β†’ False but startsWith("app") β†’ True β€” "app" is only a prefix, not a stored word.
  • Then insert("app"), and now search("app") β†’ True β€” the prefix became a full word too.

Constraints

  • 1 <= len(word), len(prefix) <= 2000
  • All strings consist of lowercase English letters a–z only.
  • At most 3 * 10^4 calls total to insert, search, and startsWith.

Think about it first

Hint 1 Storing the words in a hash set makes search trivial β€” but how would you answer startsWith without scanning every stored word?
Hint 2 Words that share a prefix can share storage. Picture a tree where the root is the empty string and each edge is labeled with one letter; a word is the path of letters from the root.
Hint 3 Give each node a dict from letter to child node plus a boolean is_end. insert walks the path creating missing nodes and marks the last one; search and startsWith both walk the path, differing only in whether they check is_end at the end.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.