Skip to lesson

A trie stores strings along character paths, providing fast prefix matching in O(L) time.

Trie structure and node representation

A trie (prefix tree) stores strings character by character along paths from the root, so words with the same prefix share nodes and prefix searches are fast.

A trie (prefix tree) stores words along character paths, so words that start the same share the same nodes. Each TrieNode holds child links and a flag isEndOfWord.

Java
static class TrieNode {    TrieNode[] children = new TrieNode[26];  // one link per letter, 'a' to 'z'    boolean isEndOfWord;                     // true if a whole word ends at this node}

A HashSet needs a scan of every word to answer a prefix query, O(N * L) for N words of length L. A trie follows one path: app, apple and apply all share the path root, a, p, p.

The isEndOfWord flag says a whole word finishes at this node. Nodes without it are only waypoints toward longer words.

Core operations: insert, search, and startsWith

To insert a word, walk from the root one character at a time, creating any missing child, and mark the last node as the end of a word. Insert, search and startsWith each take O(L) time for a word of length L.

Inserting car, cat and cow into a trie

Step 1 of 4

rootcaortw
An empty trie holds only the root. Grey nodes do not exist yet.

Example 1 · Array-Based Trie Implementation

Main.javaJava
public class Main {    static class TrieNode {        TrieNode[] children = new TrieNode[26];        boolean isEndOfWord = false;    }
    static class Trie {        private TrieNode root = new TrieNode();
        public void insert(String word) {            TrieNode curr = root;            for (char c : word.toCharArray()) {                int idx = c - 'a';                if (curr.children[idx] == null) {                    curr.children[idx] = new TrieNode();                }                curr = curr.children[idx];            }            curr.isEndOfWord = true;        }
        public boolean search(String word) {            TrieNode curr = root;            for (char c : word.toCharArray()) {                int idx = c - 'a';                if (curr.children[idx] == null) return false;                curr = curr.children[idx];            }            return curr.isEndOfWord;        }
        public boolean startsWith(String prefix) {            TrieNode curr = root;            for (char c : prefix.toCharArray()) {                int idx = c - 'a';                if (curr.children[idx] == null) return false;                curr = curr.children[idx];            }            return true;        }    }
    public static void main(String[] args) {        Trie trie = new Trie();        trie.insert("apple");        System.out.println("Search apple: " + trie.search("apple"));        System.out.println("Search app: " + trie.search("app"));        System.out.println("StartsWith app: " + trie.startsWith("app"));        trie.insert("app");        System.out.println("Search app after insert: " + trie.search("app"));    }}
Output
Search apple: true
Search app: false
StartsWith app: true
Search app after insert: true

What this code does

  • insert builds nodes for 'apple' and sets isEndOfWord on the final node.
  • search('app') returns false initially because isEndOfWord is false.
  • startsWith('app') returns true because the prefix path exists.

Search follows the same path and returns false at the first missing child. When all characters match, it returns the isEndOfWord flag.

startsWith follows the prefix characters and returns true if the whole path exists, whatever the isEndOfWord flag says.

Order of execution

Put trie insert in order

Insert one word into a trie. Put the steps in the order the code runs them.

Array children versus map children

Trie children can be a fixed array TrieNode[26] (index c - 'a') or a HashMap<Character, TrieNode>. The array is fast; the map handles any character and wastes less memory.

Example 2 · Map-Based Trie for Universal Characters

Main.javaJava
import java.util.HashMap;import java.util.Map;
public class Main {    static class MapTrieNode {        Map<Character, MapTrieNode> children = new HashMap<>();        boolean isWord = false;    }
    static class UniversalTrie {        MapTrieNode root = new MapTrieNode();
        void insert(String s) {            MapTrieNode curr = root;            for (char c : s.toCharArray()) {                curr = curr.children.computeIfAbsent(c, k -> new MapTrieNode());            }            curr.isWord = true;        }
        boolean search(String s) {            MapTrieNode curr = root;            for (char c : s.toCharArray()) {                curr = curr.children.get(c);                if (curr == null) return false;            }            return curr.isWord;        }    }
    public static void main(String[] args) {        UniversalTrie trie = new UniversalTrie();        trie.insert("User_123");        trie.insert("User_456");        System.out.println("Search User_123: " + trie.search("User_123"));        System.out.println("Search User_789: " + trie.search("User_789"));    }}
Output
Search User_123: true
Search User_789: false

What this code does

  • HashMap children allow storing digits, underscores, and uppercase characters.
  • computeIfAbsent instantiates nodes dynamically only when branches are visited.
  • search navigates map entries safely without fixed array size bounds.

Example 3 · Pruning Words from a Trie

Main.javaJava
public class Main {    static class TrieNode {        TrieNode[] children = new TrieNode[26];        boolean isEndOfWord = false;    }
    static boolean delete(TrieNode curr, String word, int depth) {        if (curr == null) return false;
        if (depth == word.length()) {            if (!curr.isEndOfWord) return false;            curr.isEndOfWord = false;            return isEmpty(curr);        }
        int idx = word.charAt(depth) - 'a';        if (delete(curr.children[idx], word, depth + 1)) {            curr.children[idx] = null;            return !curr.isEndOfWord && isEmpty(curr);        }        return false;    }
    static boolean isEmpty(TrieNode node) {        for (TrieNode child : node.children) {            if (child != null) return false;        }        return true;    }
    public static void main(String[] args) {        TrieNode root = new TrieNode();        // Insert "car" and "cart"        root.children['c' - 'a'] = new TrieNode();        TrieNode cNode = root.children['c' - 'a'];        cNode.children['a' - 'a'] = new TrieNode();        TrieNode aNode = cNode.children['a' - 'a'];        aNode.children['r' - 'a'] = new TrieNode();        TrieNode rNode = aNode.children['r' - 'a'];        rNode.isEndOfWord = true; // "car"
        delete(root, "car", 0);        System.out.println("Is 'car' word still present: " + rNode.isEndOfWord);    }}
Output
Is 'car' word still present: false

What this code does

  • delete clears isEndOfWord when reaching the target word depth.
  • Nodes with no other active branches are pruned bottom-up.
  • Common prefix paths for surviving words remain intact.

The array gives O(1) lookups and good cache behaviour, but sparse nodes hold many unused slots.

The map supports symbols, digits and Unicode and allocates only the children that exist, at the cost of hashing and wrapper objects.

Next step

Check your understanding

10 quick questions