Problem
A trie, or prefix tree, is a tree that stores a set of strings. Each edge of the tree holds one letter. Words that start with the same letters share the same path from the root, the first node of the tree.
A prefix of a string is a part at the start of the string. For example, ca is a prefix of cart.
Write the class Trie with these operations:
Trie() creates an empty trie. insert(word) adds the string word to the trie. search(word) returns true if the trie has the string word, and false if it does not. startsWith(prefix) returns true if a string in the trie starts with prefix, and false if no string does.
Example 1
- Input:
- ["Trie","insert","search","startsWith","search"] [[],["planet"],["plan"],["plan"],["planet"]]
- Output:
- [null,null,false,true,true]
- Explanation:
- The trie has
planetbut notplan. Thus,search("plan")returnsfalse, butstartsWith("plan")returnstrue.
Example 2
- Input:
- ["Trie","insert","insert","startsWith","startsWith","search"] [[],["dog"],["dot"],["do"],["da"],["do"]]
- Output:
- [null,null,null,true,false,false]
- Explanation:
dois a prefix ofdoganddot. The trie does not have the worddo.
Constraints
- 1 <= word.length, prefix.length <= 2000
- word and prefix contain only lowercase English letters.
- At most 3 * 10^4 calls in total to insert, search and startsWith
SysRound wrote this statement. A reference solution checks every example.
Related questions
Continue with questions that share topics or the same question type.
- Implement Trie II (Prefix Tree)
Coding
- Implement an extensible prefix tree
Coding · Data Structure Design · Trees
- They asked me a prefix tree leetcode question
Coding
- All Nodes Distance K in Binary Tree
Coding · Binary Tree · Breadth-First Search · Depth-First Search
Sources · 1 reference
These records explain where the question appears. A company tag or candidate report does not guarantee a future interview question.
Hello Interview · 2 records
Nielsen
Leetcode 208. Implement Trie (Prefix Tree)
Reported Apr 30, 2026 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View sourceTikTok
Leetcode 208. Implement Trie (Prefix Tree)
Reported Mar 6, 2025 · 1 source report
SENIOR
Source snapshot: Nov 12, 2026
View source