Browse Curriculum
Trie
Medium

Implement Trie (Prefix Tree)

Design a data structure that supports insert, search, and startsWith.

Problem Description

Implement Trie class:

  • insert(word): Inserts string word.
  • search(word): Returns true if string word is in the trie.
  • startsWith(prefix): Returns true if there is a previously inserted string having prefix.

Interactive Visualization

Step 1 / 1

Visualization coming soon...

Initializing...

1x

Watch how insert creates new nodes only when necessary, and search traverses existing paths.

Algorithm Strategy

  1. Node Structure: Each node contains a map/array of size 26 (for 'a'-'z') and a boolean isEnd.
  2. Insert: Traverse down; create nodes if missing. Mark last node as isEnd.
  3. Search: Traverse down; if node missing -> return false. At end, return node.isEnd.
  4. StartsWith: Traverse down; if node missing -> return false. If loop finishes, return true.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.