#208

Implement Trie (Prefix Tree)

Medium Trie basics

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Build a trie with insert(word), search(word) (exact word) and startsWith(prefix).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: build insert, search and startsWith.

Why this works: walk one node per letter; search also needs the end flag, startsWith doesn't.

Example: insert "apple"

search "app" → path exists, but no end flag → falsestartsWith "app" → true

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning true from search when the word is only a prefix of an inserted word — check the end flag.

Solve on LeetCode ↗
Complexity
  • Time: O(L) per operation.
  • Space: O(total characters inserted).
Topic: Trie
🎬 Episode 97: video coming soon