Browse curriculum

FAANGPrep Sprint

Implement Trie (Prefix Tree), LeetCode 208

Implement Trie (Prefix Tree), LeetCode 208: design a data structure that supports insert, search, and startsWith.

Problem Description

Implement Trie class:

  • insert(word): Inserts string word.
  • search(word): Returns true if string word is in the trie.
  • startsWith(prefix): Returns true if there is a previously inserted string having prefix.

Interactive Visualization

GREEN = END OF A STORED WORD

INSERT

Operation

insert("apple")

Nodes

0

Returns

:

 

insert("apple"): start at the root

Next

the root has no 'a' child: create one

Operations

Legend & Complexity

The node the operation is on

The path this operation has walked

A node marked as the end of an inserted word

No child for the next character: search or startsWith returns false

Each operation

O(L)

Space

O(total chars)

Watch how insert creates new nodes only when necessary, and search traverses existing paths.

Algorithm Strategy

  1. Node Structure: Each node contains a map/array of size 26 (for 'a'-'z') and a boolean isEnd.
  2. Insert: Traverse down; create nodes if missing. Mark last node as isEnd.
  3. Search: Traverse down; if node missing -> return false. At end, return node.isEnd.
  4. StartsWith: Traverse down; if node missing -> return false. If loop finishes, return true.

Dry Run: Insert 'cat'

Char Node Exists? Action
'c' No Create 'c' node. Move to 'c'.
'a' No Create 'a' node. Move to 'a'.
't' No Create 't' node. Move to 't'.
End - Mark 't' node as isEnd=True.

Solution

O(L) Time per operation where L is word length.

Implement Trie (Prefix Tree) Code
1var Trie = function() {
2 this.children = {};
3 this.isEnd = false;
4};
5
6Trie.prototype.insert = function(word) {
7 let node = this;
8 for(const char of word) {
9 if(!node.children[char]) {
10 node.children[char] = new Trie();
11 }
12 node = node.children[char];
13 }
14 node.isEnd = true;
15};
16
17Trie.prototype.search = function(word) {
18 let node = this;
19 for(const char of word) {
20 if(!node.children[char]) return false;
21 node = node.children[char];
22 }
23 return node.isEnd;
24};
25
26Trie.prototype.startsWith = function(prefix) {
27 let node = this;
28 for(const char of prefix) {
29 if(!node.children[char]) return false;
30 node = node.children[char];
31 }
32 return true;
33};

Implement Trie (Prefix Tree) in Python, Java, C++, TypeScript and C

Implement Trie (Prefix Tree) in Python
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root
        for char in word:
            if char not in node.children:
                node.children[char] = TrieNode()
            node = node.children[char]
        node.is_end = True

    def search(self, word: str) -> bool:
        node = self.root
        for char in word:
            if char not in node.children:
                return False
            node = node.children[char]
        return node.is_end

    def startsWith(self, prefix: str) -> bool:
        node = self.root
        for char in prefix:
            if char not in node.children:
                return False
            node = node.children[char]
        return True
Implement Trie (Prefix Tree) in Java
class Trie {
    class TrieNode {
        TrieNode[] children;
        boolean isEnd;
        public TrieNode() {
            children = new TrieNode[26];
            isEnd = false;
        }
    }
    
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode node = root;
        for(char c : word.toCharArray()) {
            int idx = c - 'a';
            if(node.children[idx] == null) {
                node.children[idx] = new TrieNode();
            }
            node = node.children[idx];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        TrieNode node = root;
        for(char c : word.toCharArray()) {
            int idx = c - 'a';
            if(node.children[idx] == null) return false;
            node = node.children[idx];
        }
        return node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode node = root;
        for(char c : prefix.toCharArray()) {
            int idx = c - 'a';
            if(node.children[idx] == null) return false;
            node = node.children[idx];
        }
        return true;
    }
}
Implement Trie (Prefix Tree) in C++
class Trie {
    struct TrieNode {
        TrieNode* children[26];
        bool isEnd;
        TrieNode() {
            for(int i=0; i<26; i++) children[i] = nullptr;
            isEnd = false;
        }
    };
    TrieNode* root;
    
public:
    Trie() {
        root = new TrieNode();
    }
    
    void insert(string word) {
        TrieNode* node = root;
        for(char c : word) {
            int idx = c - 'a';
            if(!node->children[idx]) node->children[idx] = new TrieNode();
            node = node->children[idx];
        }
        node->isEnd = true;
    }
    
    bool search(string word) {
        TrieNode* node = root;
        for(char c : word) {
            int idx = c - 'a';
            if(!node->children[idx]) return false;
            node = node->children[idx];
        }
        return node->isEnd;
    }
    
    bool startsWith(string prefix) {
        TrieNode* node = root;
        for(char c : prefix) {
            int idx = c - 'a';
            if(!node->children[idx]) return false;
            node = node->children[idx];
        }
        return true;
    }
};
Implement Trie (Prefix Tree) in TypeScript
class Trie {
    children: { [key: string]: Trie };
    isEnd: boolean;

    constructor() {
        this.children = {};
        this.isEnd = false;
    }

    insert(word: string): void {
        let node: Trie = this;
        for (const char of word) {
            if (!node.children[char]) {
                node.children[char] = new Trie();
            }
            node = node.children[char];
        }
        node.isEnd = true;
    }

    search(word: string): boolean {
        let node: Trie = this;
        for (const char of word) {
            if (!node.children[char]) return false;
            node = node.children[char];
        }
        return node.isEnd;
    }

    startsWith(prefix: string): boolean {
        let node: Trie = this;
        for (const char of prefix) {
            if (!node.children[char]) return false;
            node = node.children[char];
        }
        return true;
    }
}
Implement Trie (Prefix Tree) in C
typedef struct Trie {
    struct Trie* children[26];
    bool isEnd;
} Trie;

Trie* trieCreate() {
    Trie* obj = (Trie*)malloc(sizeof(Trie));
    for(int i=0; i<26; i++) obj->children[i] = NULL;
    obj->isEnd = false;
    return obj;
}

void trieInsert(Trie* obj, char * word) {
    Trie* node = obj;
    for(int i=0; word[i] != '\0'; i++) {
        int idx = word[i] - 'a';
        if(node->children[idx] == NULL) {
            node->children[idx] = trieCreate();
        }
        node = node->children[idx];
    }
    node->isEnd = true;
}

bool trieSearch(Trie* obj, char * word) {
    Trie* node = obj;
    for(int i=0; word[i] != '\0'; i++) {
        int idx = word[i] - 'a';
        if(node->children[idx] == NULL) return false;
        node = node->children[idx];
    }
    return node->isEnd;
}

bool trieStartsWith(Trie* obj, char * prefix) {
    Trie* node = obj;
    for(int i=0; prefix[i] != '\0'; i++) {
        int idx = prefix[i] - 'a';
        if(node->children[idx] == NULL) return false;
        node = node->children[idx];
    }
    return true;
}

void trieFree(Trie* obj) {
    for(int i=0; i<26; i++) {
        if(obj->children[i]) trieFree(obj->children[i]);
    }
    free(obj);
}

Edge Cases & Common Mistakes

Check for:

  • Word is Prefix: Searching for 'app' when 'apple' exists. Should return False (unless 'app' was inserted independently).

  • Prefix Search: startsWith('app') should return True if 'apple' exists.

  • Duplication: Inserting 'app' twice shouldn't break anything.