Implement Trie (Prefix Tree)

MediumTrie · Design🧩 TrieLeetCode #208 ↗Updated

Problem

Build a Trie class for lowercase words with three operations: insert(word) stores a word, search(word) tells whether that exact word was inserted, and startsWith(prefix) tells whether any inserted word begins with the given prefix.
Inputinsert("apple") search("apple")Outputtrue
Inputsearch("app") startsWith("app")Outputfalse, true
Inputinsert("app") search("app")Outputtrue

1 ≤ word.length, prefix.length ≤ 2000  ·  lowercase letters only  ·  ≤ 3·104 calls in total

Try it yourself

Java
class Trie {
    public void insert(String word) {
        
    }

    public boolean search(String word) {
        
    }

    public boolean startsWith(String prefix) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Words that share a prefix should share storage. A tree where each edge is a letter makes every prefix a single path from the root, so all three operations just walk L steps — independent of how many words are stored.
PatternTrie

Instinct Many words, shared prefixes, and questions like "starts with", autocomplete, wildcard match or "search a board for all these words" - build a prefix tree.

Memory hack Words share their beginnings, so store each beginning once - walk one letter per step, and an end flag marks where a real word stops.

Open the Trie guide →

Approaches

Brute ForceHashSet + Linear Prefix Scan

Time O(L) insert/search, O(N·L) startsWithSpace O(S)

A HashSet answers exact lookups in O(L) (hashing the word). For startsWith there is no shortcut: test every stored word with String.startsWith. N = words stored, S = total characters.

Java
class Trie {
    private final Set<String> words = new HashSet<>();

    public void insert(String word) { words.add(word); }

    public boolean search(String word) { return words.contains(word); }

    public boolean startsWith(String prefix) {
        for (String w : words) {
            if (w.startsWith(prefix)) return true;
        }
        return false;
    }
}

Exact search is fast, but prefix queries degrade linearly with N.

At a glance

LevelApproachTimeSpace
Brute ForceHashSet + Linear Prefix ScanO(L) insert/search, O(N·L) startsWithO(S)
BetterSorted Set (TreeSet) + ceilingO(L log N) all opsO(S)
OptimalTrie with children[26]O(L) all opsO(26·S)
Common pitfalls
  • Returning true from search just because the path exists — check isEnd.
  • Allocating a new node on every insert step — overwrites existing subtrees.
  • Sharing one helper for search/startsWith but forgetting their end conditions differ.
Interview tips
  • Clarify the alphabet: fixed 26 letters → array; Unicode → hash map.
  • Factor the common path walk into one helper to avoid duplicated loops.
  • Discuss memory: 26 pointers per node vs sharing of common prefixes.
Pattern
Trie → many prefix lookups over a dictionary of strings (autocomplete, word search).
My notes saved in this browser