Implement Trie (Prefix Tree)

Medium~25 min

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • insert(word) Inserts the string word into the trie.
  • search(word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • startsWith(prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Examples

Example 1
Input: ["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output: [null, null, true, false, true, null, true]
Explanation: Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return true trie.search("app"); // return false ("app" not inserted) trie.startsWith("app"); // return true ("apple" starts with "app") trie.insert("app"); trie.search("app"); // return true ("app" now inserted)

Constraints

  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters
  • At most 3 * 10^4 calls in total will be made to insert, search, and startsWith
  • Expected time complexity: O(m) per operation
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run