Implement Trie (Prefix Tree)
MediumPython 3TriesStrings
A trie (prefix tree) stores strings so that lookups by whole word or by
prefix run in time proportional to the query length. Implement it:
- insert(word): add `word` to the trie.
- search(word): return True if `word` was inserted (exact match).
- starts_with(prefix): return True if any inserted word starts with
`prefix` (a word counts as a prefix of itself).Constraints: - words and prefixes are non-empty strings of lowercase English letters - insert may be called with the same word more than once
Examples:
t = Trie()
t.insert("apple")
t.search("apple") -> True
t.search("app") -> False (no such whole word)
t.starts_with("app") -> True
t.insert("app")
t.search("app") -> TruePython 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.
Loading the editor…