</>

208. Implement Trie (Prefix Tree)

Medium NeetCode 150
Tries Time O(m) Space O(m)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Tries
Time
O(m)
Space
O(m)

Standard Solution (C++)

SummaryBuild a trie (prefix tree) that efficiently stores a collection of strings and answers two kinds of membership queries: whether a string has been inserted in full, and whether any inserted string begins with a given prefix.

Approach
  • Each trie node holds a fixed-size array of 26 child pointers (one per lowercase letter) and an isEnd flag marking complete words.
  • insert walks character-by-character, allocating new nodes on demand, then sets isEnd at the terminal node.
  • search traverses the same path and returns true only when the path exists and the final node is marked as a word end.
  • startsWith is identical to search but omits the isEnd check — any valid path through the trie constitutes a matching prefix.
#include <string>
#include <array>
using namespace std;

struct TrieNode {
    array<TrieNode*, 26> children{};  // zero-initialized to nullptr
    bool isEnd = false;
};

class Trie {
public:
    Trie() : root(new TrieNode()) {}

    // Insert all characters, creating nodes as needed; mark terminal.
    void insert(const string& word) {
        TrieNode* cur = root;
        for (char c : word) {
            int idx = c - 'a';
            if (!cur->children[idx])
                cur->children[idx] = new TrieNode();
            cur = cur->children[idx];
        }
        cur->isEnd = true;
    }

    // Return true iff word was previously inserted in full.
    bool search(const string& word) {
        TrieNode* node = traverse(word);
        return node && node->isEnd;
    }

    // Return true iff any inserted word starts with prefix.
    bool startsWith(const string& prefix) {
        return traverse(prefix) != nullptr;
    }

private:
    TrieNode* root;

    // Walk the trie following the characters of s; return the final node or nullptr.
    TrieNode* traverse(const string& s) {
        TrieNode* cur = root;
        for (char c : s) {
            cur = cur->children[c - 'a'];
            if (!cur) return nullptr;
        }
        return cur;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
Time O(m) per operation, where m is the length of the input string Space O(m) per insert (up to m new nodes); O(total characters inserted) overall

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <string>
using namespace std;

class TrieNode {
public:
    bool isWord;
    TrieNode *child[26];
    TrieNode(){
        isWord=false;
        for(auto &a: child)
            a=nullptr;
    }
};
class Trie {
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(string word) {
        TrieNode* p=root;
        for(auto &a: word){
            int i=a-'a';
            if(!p->child[i])
                p->child[i]=new TrieNode();
            p=p->child[i];
        }
        p->isWord=true;
    }
    
    bool search(string word) {
        TrieNode* p=root;
        for(auto &a: word){
            int i=a-'a';
            if(!p->child[i])
                return false;
            p=p->child[i];
        }
        return p->isWord;
    }
    
    bool startsWith(string prefix) {
        TrieNode *p = root;
        for (auto &a: prefix)
        {
            int i = a - 'a';
            if(!p->child[i])
                return false;
            p=p->child[i];
        }
        
        return true;
    }

private:
    TrieNode* root;
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

// Time Complexity: O(m) for insert, search, and startsWith, where m is the length of the input string (word or prefix).
// Space Complexity: O(m) for insert, since we may need to create up to m new TrieNodes in the worst case. The space complexity for search and startsWith is O(1) since they only use a constant amount of extra space.
Time O(m) Space O(m)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern