Skip to content
Veltoryx Technologies
FreeProblem 149● Mediumleetcode ↗4 min readUpdated 30 October 2026

Implement Trie (Prefix Tree)

Design and implement a 26-way prefix tree with insert, search, and startsWith operations in O(L) time.

01The problem

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

02How to spot it

  • Many words share common prefixes.
  • Queries require checking whether a word exists or whether any word starts with a given prefix.
  • Standard hash sets can check exact words in O(L) time, but checking startsWith(prefix) would require storing all prefixes of all words, consuming O(N · L^2) memory.
  • A Trie achieves O(L) lookup and prefix verification while sharing prefix storage.

03Pseudocode

text
insert(w):
  node = root
  for ch in w:
    create child ch if missing
    node = child ch
  node.isWord = true
search(w): walk(w) exists and isWord
startsWith(p): walk(p) exists

04Watch it work

Visualizer · step through the algorithmops = [["insert","apple"],["search","apple"],["search","app"],["startsWith","app"],["insert","app"],["search","app"]]

trie state

empty root

Initialize Trie root with empty 26-way children slots and isWord = false.

Pseudocode

  1. insert(w):
  2. node = root
  3. for ch in w:
  4. create child ch if missing
  5. node = child ch
  6. node.isWord = true
  7. search(w): walk(w) exists and isWord
  8. startsWith(p): walk(p) exists

Variables

storedWords
step 1 / 7

05Step-by-step dry run

  1. insert("apple"):
    • Walk from root: create nodes for 'a', 'p', 'p', 'l', 'e'.
    • Mark terminal node for 'e' with isWord = true.
  2. search("apple"):
    • Follow path a -> p -> p -> l -> e.
    • Node exists and isWord == true -> return true.
  3. search("app"):
    • Follow path a -> p -> p.
    • Node exists, but isWord == false (only "apple" was inserted) -> return false.
  4. startsWith("app"):
    • Follow path a -> p -> p.
    • Node exists -> return true (words like "apple" branch below it).
  5. insert("app"):
    • Follow path a -> p -> p (no new nodes needed).
    • Set isWord = true on the second 'p' node.
  6. search("app"):
    • Follow path a -> p -> p.
    • Node exists and now isWord == true -> return true.

06Java solution

java
public class Main {
    static class Trie {
        private final Trie[] next = new Trie[26];
        private boolean isWord;

        public Trie() {}

        public void insert(String word) {
            Trie node = this;
            for (char ch : word.toCharArray()) {
                int i = ch - 'a';
                if (node.next[i] == null) {
                    node.next[i] = new Trie();
                }
                node = node.next[i];
            }
            node.isWord = true;
        }

        public boolean search(String word) {
            Trie node = walk(word);
            return node != null && node.isWord;
        }

        public boolean startsWith(String prefix) {
            return walk(prefix) != null;
        }

        private Trie walk(String s) {
            Trie node = this;
            for (char ch : s.toCharArray()) {
                node = node.next[ch - 'a'];
                if (node == null) return null;
            }
            return node;
        }
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("apple");
        System.out.println(trie.search("apple"));
        System.out.println(trie.search("app"));
        System.out.println(trie.startsWith("app"));
        trie.insert("app");
        System.out.println(trie.search("app"));
    }
}
Expected output
true
false
true
true

07Why it works

Every stored word corresponds to exactly one path from the root, and words with a common prefix share that part of the path. Following a string letter by letter either fails (no word has this prefix) or reaches a node. The helper method walk(s) encapsulates path traversal, so search and startsWith share identical logic except that search additionally verifies node.isWord == true.

08Time and space

  • Time complexity:
    • insert(word): O(L) where L is the length of the word.
    • search(word): O(L) character comparisons.
    • startsWith(prefix): O(P) where P is prefix length.
  • Space complexity: O(totalCharacters · 26) in the worst case where no words share prefixes.

09Edge cases

  • search before any insertion: walk(word) returns null -> returns false.
  • Inserting a prefix of an already inserted word: Reuses existing path; only sets isWord = true on the existing node without allocating new nodes.
  • startsWith(""): Empty prefix matches root -> returns true.

10Common mistakes

  • Returning true in search when node != null but !node.isWord: A path existing only means the string is a prefix; checking node.isWord is necessary to confirm a full word.
  • Creating new nodes during search: Search should only read existing links; creating nodes pollutes the trie with fake paths.

11Other approaches

  • HashMap for children: Map<Character, TrieNode> next saves memory when alphabet size is large or sparse (e.g. Unicode), but an array of 26 references is faster for lowercase English letters.

12In the interview

  1. Mention the shared helper method: "I will implement a private walk(String s) helper method to avoid duplicating the letter-by-letter traversal between search and startsWith."
  2. Note alphabet size: for a-z, an array of 26 elements gives instant O(1) index lookups with minimal overhead.

13Quiz

What distinguishes search(word) from startsWith(prefix) in a Trie?

  • (Recommended) search requires node.isWord to be true, while startsWith only requires the path to exist
  • search is O(1) while startsWith is O(n)
  • startsWith creates nodes while search does not
  • search only inspects the root node

Answer: search requires node.isWord to be true, while startsWith only requires the path to exist. A prefix path may exist in the trie because a longer word was inserted, but it is only a valid word if isWord was explicitly flagged.

14Solve it yourself

Open LeetCode #208 and submit the Trie implementation.