algoadvance

Leetcode 208. Implement Trie (Prefix Tree)

Problem Statement

Implement a trie with insert, search, and startsWith methods.

Clarifying Questions

  1. Q: Can we assume all inputs are lowercase English letters? A: Yes, all inputs are guaranteed to be lowercase English letters (a-z).

  2. Q: What is the maximum length of word or prefix? A: You can assume that the maximum length of word or prefix is 2000.

  3. Q: Can we have duplicate insertions of the same word? A: Yes, duplicate insertions are allowed, but they should be ignored in terms of storage.

Strategy

We’ll use a class TrieNode for the nodes of the trie. Each node contains:

We then implement the Trie class using these nodes:

Code

class TrieNode {
    public TrieNode[] children;
    public boolean isEnd;
    
    public TrieNode() {
        // Initialize children for 26 lowercase English letters
        children = new TrieNode[26];
        isEnd = false;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (node.children[index] == null) {
                node.children[index] = new TrieNode();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    public boolean search(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (node.children[index] == null) {
                return false;
            }
            node = node.children[index];
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for (char c : prefix.toCharArray()) {
            int index = c - 'a';
            if (node.children[index] == null) {
                return false;
            }
            node = node.children[index];
        }
        return true;
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI