All problems
MediumTrie

Implement Trie (Prefix Tree)

googleamazonmicrosoftmetauberoraclebloomberg

A trie (pronounced "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.
  • void insert(String word) — Inserts the string word into the trie.
  • boolean search(String word) — Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) — Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

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");   // Inserts "apple" into the trie
trie.search("apple");   // Returns true
trie.search("app");     // Returns false ("app" was not inserted)
trie.startsWith("app"); // Returns true ("apple" starts with "app")
trie.insert("app");     // Inserts "app" into the trie
trie.search("app");     // Returns true ("app" is now in the trie)

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: After inserting "apple", searching for "apple" returns true but "app" returns false since it wasn't inserted. startsWith("app") returns true because "apple" has prefix "app". After inserting "app", searching for "app" returns true.

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

Optimal Complexity

Time

O(m) per operation, where m is the word/prefix length

Space

O(n * m) total, where n is the number of words inserted

Practice this problem with an AI interviewer

TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.

Start a free interview