208. Implement Trie (Prefix Tree) - Detailed Explanation

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

Problem Statement

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the exact string word is in the trie (i.e., was previously inserted), or false otherwise.
  • boolean startsWith(String prefix) Returns true if there is any previously inserted string that starts with the given prefix, or false otherwise.

Examples

Input
["Trie","insert","search","search","startsWith","insert","search"]
[[],       ["apple"],["apple"],["app"],    ["app"],      ["app"],["app"]]

Output
[null,     null,     true,     false,       true,        null,    true]

Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false (only prefix "app" exists)
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app");     // returns true

Constraints

  • 1 ≤ word.length, prefix.length ≤ 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3·10⁴ calls in total will be made to insert, search, and startsWith.

Approach

Trie Node Structure

Each node holds:

  • An array (or map) of up to 26 child pointers, one for each lowercase letter.
  • A boolean flag isEnd indicating whether a word ends at this node.

Operations

insert(word)

  1. Start at the root node.
  2. For each character c in word:
    • Compute its index i = c - 'a'.
    • If node.children[i] is null, create a new TrieNode.
    • Move node = node.children[i].
  3. After the last character, mark node.isEnd = true.

search(word)

  1. Traverse exactly as in insert, but if at any step node.children[i] is null, return false.
  2. After processing all chars, return node.isEnd.

startsWith(prefix)

  1. Traverse as in search, but do not check isEnd.
  2. If you complete the traversal without hitting null, return true.

Complexity Analysis

  • Time: O(m) per operation (m = length of word or prefix).
  • Space: In the worst case, O(N·L) for storing all inserted words (N words of average length L), since each character may create a new node.

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Common Mistakes

  • Forgetting to mark isEnd on insert, causing search to return false for inserted words.
  • Using a map per node instead of a fixed‑size array, which increases constant factors.
  • In startsWith, accidentally requiring isEnd to be true.

Edge Cases

  • Inserting or searching the same word multiple times.
  • Searching for a prefix that is exactly an inserted word.
  • Very long words near the maximum length.
TAGS
leetcode
CONTRIBUTOR
Design Gurus Team
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Related Courses
Grokking the Coding Interview: Patterns for Coding Questions
Grokking the Coding Interview Patterns in Java, Python, JS, C++, C#, and Go. The most comprehensive course with 476 Lessons.
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
Image
One-Stop Portal For Tech Interviews.
Copyright © 2025 Design Gurus, LLC. All rights reserved.
;