Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
Implement Trie (Prefix Tree)
Problem
Design a data structure that stores a collection of lowercase words and supports three operations:
insert(word): addwordto the structure.search(word): returnTrueif exactly this word was previously inserted.startsWith(prefix): returnTrueif at least one inserted word begins withprefix.
The same word may be inserted more than once; that should not change the answers.
- Each inserted word or queried prefix is 1 to a few thousand characters long.
- All strings consist of the letters
a–zonly. - The structure should stay fast even under tens of thousands of combined calls.
Examples
insert("banana"),search("banana")→True;search("ban")→Falsebecause"ban"was never inserted as a whole word;startsWith("ban")→Truebecause"banana"starts with it.- After the above,
insert("ban"), thensearch("ban")→True. Marking the node at the end of"ban"as terminal is what flips the answer. startsWith("cat")→Falseon a structure that only holds"banana"and"ban": the root has no child forc.
Hints
- Storing words in a hash set makes
searchtrivial, but how would you answerstartsWithwithout scanning every stored word? - Words that share a prefix should share the storage for that prefix. Think of a tree where each edge is one character.
- Build a tree of nodes, each holding a map from character to child node plus a boolean "a word ends here" flag. Walk the tree character by character for all three operations.
Last reviewed 8 September 2026
Locked
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Secure payment by Stripe · instant access · refund questions: [email protected]
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.