algoadvance

Leetcode 208. Implement Trie (Prefix Tree)

Problem Statement

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

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and search a set of strings, where the keys are usually strings. The main operations of a trie are:

Clarifying Questions

  1. Character Set: Do the strings only contain lowercase English letters?

    Assumption: Yes, strings only contain ‘a’ to ‘z’.

  2. Case Sensitivity: Are the strings case-sensitive?

    Assumption: No, we can assume the strings are lowercase for simplicity.

  3. Operations Frequency: Will any operation (insert, search, startsWith) be called more frequently than others?

    Assumption: No specific operation is highlighted as being more frequent.

Strategy

Trie Node Structure

Each node in a Trie will contain:

Insert Operation

Search Operation

startsWith Operation

Code

#include <iostream>
#include <vector>

using namespace std;

class TrieNode {
public:
    bool isEndOfWord;
    vector<TrieNode*> children;
    
    TrieNode() : children(26, nullptr), isEndOfWord(false) {}
};

class Trie {
private:
    TrieNode* root;
    
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(string word) {
        TrieNode* node = root;
        for(char c : word) {
            int index = c - 'a';
            if (!node->children[index]) {
                node->children[index] = new TrieNode();
            }
            node = node->children[index];
        }
        node->isEndOfWord = true;
    }
    
    bool search(string word) {
        TrieNode* node = root;
        for(char c : word) {
            int index = c - 'a';
            if (!node->children[index]) {
                return false;
            }
            node = node->children[index];
        }
        return node != nullptr && node->isEndOfWord;
    }
    
    bool startsWith(string prefix) {
        TrieNode* node = root;
        for(char c : prefix) {
            int index = c - 'a';
            if (!node->children[index]) {
                return false;
            }
            node = node->children[index];
        }
        return node != nullptr;
    }
};

Time Complexity

Given these complexities, the trie operations will be very efficient, particularly for string sets with a large number of common prefixes.

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