CodingNodes / Tries / Implement Trie (Prefix Tree) System design Space play · ←→ step · R restart

Problem

A trie is a tree that stores words one letter per edge, so words that share a beginning share a path. Build a class Trie with these operations:

  • Trie() creates an empty trie.
  • insert(word) stores word.
  • search(word) returns true only if exactly word was inserted earlier.
  • startsWith(prefix) returns true if any inserted word begins with prefix.

The input is a list of calls and their arguments; the output lists what each call returns (null for the constructor and for insert).

Constraints

  • 1 ≤ word.length, prefix.length ≤ 2000
  • word and prefix use only lowercase English letters
  • At most 3 · 10⁴ calls in total

Examples: pick one to animate

Solutions

TimeO(L) SpaceO(total letters)

Time: insert, search and startsWith each walk one edge per letter of the argument, L letters in all.

Space: Each inserted word adds at most one new node per letter, and shared prefixes are stored once.

Every node holds a map from a letter to its child and a flag that says "a word ends here". insert walks the letters, creating missing children, then sets the flag. search and startsWith share one helper that walks the letters and returns the node it reaches (or null); search also needs the flag, startsWith does not.