Implement Trie (Prefix Tree)

MediumTreestrie

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 needed

Problem

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

Input: ["Trie","insert","search","search","startsWith","insert","search"] [[],["car"],["car"],["ca"],["ca"],["ca"],["ca"]]
Output: [null,null,true,false,true,null,true]
"car" is a stored word. "ca" is only a prefix until it is inserted itself, after which `search("ca")` is true.
Input: ["Trie","insert","startsWith","search","startsWith"] [[],["dog"],["dogs"],["do"],["d"]]
Output: [null,null,false,false,true]
"dogs" is longer than any stored word, "do" was never inserted as a word, and "d" prefixes "dog".

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.

More trie problems