Implement a trie
Standard · Write code · about 15 min
Build a trie and run a list of commands on it. insert W adds the word W. search W is true only when W was inserted as a whole word. startsWith W is true when some inserted word begins with W.
Return the results of the search and startsWith commands in order, as the text true or false. insert produces no output.
Example 1
Input:
[["insert cat","insert car","search car","startsWith ca","search ca"]]
Output:
["true","true","false"]
ca is a prefix of cat and car, but ca was never inserted as a word.
Example 2
Input:
[["insert go","search gone","startsWith g"]]
Output:
["false","true"]
gone needs edges that do not exist.
Constraints
- 0 ≤ commands.length ≤ 2,000
- Each command is
insert W,search WorstartsWith W - W has 1 to 20 lowercase letters
Learn the idea first: Tries: insert, search, prefix, a visual lesson.
More Tries: insert, search, prefix problems
- Node count Warm-up
- Starts-with Warm-up
- Longest common prefix Standard
- Trace a search Standard
- Word dictionary with wildcard Challenge