medium

Implement Trie (Prefix Tree)

Implement a data structure storing lowercase words with three operations: insert(word), search(word) returning whether the exact word exists, and startsWith(prefix) returning whether any stored word begins with the prefix.

Constraints
  • 1 ≤ word.length ≤ 2000
  • Lowercase English letters
  • At most 3 · 10^4 operations
Examples
in: insert("apple"), search("apple"), search("app"), startsWith("app"), insert("app"), search("app")
out: true, false, true, true
Recognition clues
  • Prefix queries
  • Shared prefixes should share storage
  • Lookups linear in the word length, independent of dictionary size
Pattern
Trie

Prefix questions over a set of strings are answered by walking a tree keyed by characters, costing O(L) per query regardless of how many words are stored. It also lets a grid DFS abort as soon as the current path is not a prefix of any word, which is what makes multi-word search feasible.

Solution

Each node holds an array or map of child links keyed by character and an end flag. insert walks the word creating missing children and marks the last node as terminal. search walks the word and returns whether it reaches a node with end set; startsWith returns whether the walk completes at all. All three cost time proportional to the string length.

time O(L) per operationspace O(total characters)
Alternative approaches
  • A hash set of all prefixes supports startsWith but wastes O(total L^2) memory. A sorted array with binary search gives O(L log n).
Code it yourself
Solve in
Hints: