Implement Trie (Prefix Tree)
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
A trie stores strings character by character in a tree so that lookups and prefix checks take time proportional to the query length, not to the number of stored words. Build one.
Implement:
- Trie() creates an empty trie.
- insert(word) adds word (inserting the same word twice is harmless).
- search(word) returns true only if word itself was inserted earlier.
- startsWith(prefix) returns true if **any** inserted word begins with prefix (a word counts as a prefix of itself).
All strings consist of lowercase English letters. Each operation should run in O(length of its argument).
Examples
Constraints
- 1 <= word.length, prefix.length <= 2000
- Only lowercase English letters.
- At most 3 * 10^4 calls to `insert`, `search` and `startsWith` combined.
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.