Skip to content
AI360Xpert
Back to Tries
Medium

Implement Trie (Prefix Tree)

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 very efficient 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.

Examples

Input:["Trie", "insert", "search", "search", "startsWith", "insert", "search"] [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output:[null, null, true, false, true, null, true]
Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // return True trie.search("app"); // return False trie.startsWith("app"); // return True trie.insert("app"); trie.search("app"); // return 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.

Hash Map (or Array) Node

Approach

Create a `TrieNode` class. Each node has a hash map (or an array of size 26) representing its children, and a boolean flag `isEndOfWord`. For `insert`, iterate through the characters of the word. If a character is not in the current node's children, add a new `TrieNode`. Then move to the child node. Finally, set `isEndOfWord = true` at the last node. `search` and `startsWith` follow a similar traversal pattern. If a character is missing, return `false`. For `search`, check the `isEndOfWord` flag at the end, while `startsWith` just returns `true` if the traversal finishes successfully.

Complexity Analysis

Time Complexity
O(m) per operation
Space Complexity
O(m * N)

Where m is the length of the word/prefix and N is the number of inserted words.

Solution.java
class TrieNode {    TrieNode[] children;    boolean isEndOfWord;        public TrieNode() {        children = new TrieNode[26];        isEndOfWord = false;    }}
class Trie {    private TrieNode root;
    public Trie() {        root = new TrieNode();    }        public void insert(String word) {        TrieNode curr = root;        for (char c : word.toCharArray()) {            int index = c - 'a';            if (curr.children[index] == null) {                curr.children[index] = new TrieNode();            }            curr = curr.children[index];        }        curr.isEndOfWord = true;    }        public boolean search(String word) {        TrieNode curr = root;        for (char c : word.toCharArray()) {            int index = c - 'a';            if (curr.children[index] == null) {                return false;            }            curr = curr.children[index];        }        return curr.isEndOfWord;    }        public boolean startsWith(String prefix) {        TrieNode curr = root;        for (char c : prefix.toCharArray()) {            int index = c - 'a';            if (curr.children[index] == null) {                return false;            }            curr = curr.children[index];        }        return true;    }}