208. Implement Trie (Prefix Tree) - Detailed Explanation

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
59. Spiral Matrix II - Detailed Explanation
Learn to solve Leetcode 59. Spiral Matrix II with multiple approaches.
3066. Minimum Operations to Exceed Threshold Value II - Detailed Explanation
Learn to solve Leetcode 3066. Minimum Operations to Exceed Threshold Value II with multiple approaches.
236. Lowest Common Ancestor of a Binary Tree - Detailed Explanation
Learn to solve Leetcode 236. Lowest Common Ancestor of a Binary Tree with multiple approaches.
2349. Design a Number Container System - Detailed Explanation
Learn to solve Leetcode 2349. Design a Number Container System with multiple approaches.
468. Validate IP Address - Detailed Explanation
Learn to solve Leetcode 468. Validate IP Address with multiple approaches.
759. Employee Free Time - Detailed Explanation
Learn to solve Leetcode 759. Employee Free Time with multiple approaches.
Related Courses
Course image
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.
4.6
Discounted price for Your Region

$197

Course image
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
3.9
Discounted price for Your Region

$72

Course image
Grokking Data Structures & Algorithms for Coding Interviews
Unlock Coding Interview Success: Dive Deep into Data Structures and Algorithms.
4
Discounted price for Your Region

$78

Image
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.