Implement Trie (Prefix Tree)
MediumTries
Design a Trie (prefix tree) class that stores lowercase words and supports these operations:
Trie()creates an empty trie.insert(word)storesword. Inserting the same word again has no extra effect.search(word)returnsTrueifworditself was inserted earlier, andFalseotherwise. Being a prefix of an inserted word is not enough.startsWith(prefix)returnsTrueif at least one inserted word begins withprefix(a word counts as beginning with itself), andFalseotherwise.
The examples list the calls made in order, and the output lists each call's return value (None for the constructor and insert).
Example 1
- Input:
- Trie(); insert("card"); search("car"); startsWith("car"); insert("car"); search("car"); search("cart")
- Output:
- [None, None, False, True, None, True, False]
- Explanation
caris a prefix ofcard, sostartsWith("car")isTruewhilesearch("car")isFalseuntilcaris inserted itself.cartwas never inserted.
Example 2
- Input:
- Trie(); insert("sun"); insert("sunset"); startsWith("sunr"); search("sunset"); startsWith("s")
- Output:
- [None, None, None, False, True, True]
- Explanation
- No word continues
sunwithr, sostartsWith("sunr")fails.sunsetwas inserted, and both words start withs.
Example 3
- Input:
- Trie(); startsWith("a"); insert("a"); search("a"); startsWith("a")
- Output:
- [None, False, None, True, True]
- Explanation
- Before any insert nothing matches. Once
ais stored, it is both a full word and a prefix of itself.
Constraints
1 <= word.length, prefix.length <= 2000wordandprefixconsist of lowercase English letters- At most
3 * 10^4calls are made toinsert,search, andstartsWithin total