1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Tries Prefix Trees
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
01Hrs
21Mins
54Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Tries Prefix Trees

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
01Hrs
21Mins
54Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Prefix Trees

Overview

A Trie (pronounced 'try', short for reTRIEval tree), also known as a Prefix Tree, is a specialized tree designed explicitly for storing and searching strings.

In a standard BST or HashMap, searching for a string like 'apple' takes time proportional to the number of elements in the structure. In a Trie, the search time depends ONLY on the length of the string itself (O(L)), completely independent of how many millions of words the tree holds.

A Trie stores characters in its nodes. The root is empty, and its children represent the first character of words. A path down the tree spells out a word. Because words with the same prefix (e.g., 'car', 'card', 'cart') share the same nodes for 'c', 'a', and 'r', Tries are incredibly space-efficient for dictionaries and are the ultimate data structure for autocomplete and spell-checking systems.

Syntax

Trie Node and Word Insertion
java
public class Trie {
    static class TrieNode {
        // Array of 26 pointers for lowercase English letters
        TrieNode[] children = new TrieNode[26];
        boolean isEndOfWord = false; // True if a word ends at this node
    }
    
    TrieNode root = new TrieNode();
    
    // O(L) Insertion, where L is word length
    public void insert(String word) {
        TrieNode current = root;
        
        for (char c : word.toCharArray()) {
            int index = c - 'a'; // Convert 'a'->0, 'b'->1, etc.
            
            if (current.children[index] == null) {
                current.children[index] = new TrieNode();
            }
            current = current.children[index]; // Move down the tree
        }
        current.isEndOfWord = true; // Mark the final node
    }
    
    // O(L) Search for an exact word
    public boolean search(String word) {
        TrieNode current = root;
        
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (current.children[index] == null) {
                return false; // Path breaks, word doesn't exist
            }
            current = current.children[index];
        }
        return current.isEndOfWord; // Must be marked as an end!
    }
}

Common Pitfalls

  • Assuming a matching prefix means a matching word. If you insert 'apple', the tree contains nodes for 'a-p-p-l-e'. If you search for 'app', the path exists, but 'app' is NOT a word. You must check if (current.isEndOfWord) at the final node.
  • Hardcoding array sizes poorly. Using TrieNode[26] is highly optimized but ONLY works for lowercase English letters (a-z). If you need uppercase, numbers, or symbols, you must use a HashMap<Character, TrieNode> instead, which slightly increases overhead.
  • High memory consumption for sparse datasets. If your dataset has very few shared prefixes, the Trie will create millions of objects. Each Node in Java has memory overhead, making an array-based Trie a memory hog if not carefully managed.

Interview Questions

Why use a Trie instead of a HashMap for storing a dictionary of words?

A HashMap is great for exact matches, but it cannot answer 'Give me all words starting with 'auto''. A Trie inherently groups words by their prefixes, making autocomplete searches (Prefix Matching) highly efficient. Additionally, for a dense dictionary, a Trie saves memory because common prefixes are shared.

How would you implement an Autocomplete system using a Trie?

First, traverse the Trie using the characters of the user's input prefix. Once you reach the node representing the last character of the prefix, perform a Depth-First Search (DFS) from that node downwards to collect all nodes marked isEndOfWord. These represent the autocomplete suggestions.

Real-World Example

Google's Search Bar Autocomplete is heavily reliant on distributed Trie-like structures. When you type 'how to co', the system instantly traverses to the 'o' node under 'c' under ' ' under 'o', etc., and returns the most popular paths ('how to code', 'how to cook').

example
java
public List<String> autocomplete(String prefix) {
    List<String> results = new ArrayList<>();
    TrieNode current = root;
    
    // 1. Navigate to the end of the prefix
    for (char c : prefix.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) return results; // No matches
        current = current.children[index];
    }
    
    // 2. DFS to find all words branching from here
    dfsFindWords(current, prefix, results);
    return results;
}

private void dfsFindWords(TrieNode node, String prefixSoFar, List<String> results) {
    if (node.isEndOfWord) results.add(prefixSoFar);
    
    for (int i = 0; i < 26; i++) {
        if (node.children[i] != null) {
            char nextChar = (char) (i + 'a');
            dfsFindWords(node.children[i], prefixSoFar + nextChar, results);
        }
    }
}

Check Your Knowledge

Test your understanding of Prefix Trees with these quick questions.

Question 1

What is the primary advantage of a Trie over a HashMap?

Question 2

What is the time complexity of searching for a word of length L in a Trie?

Question 3

Why does a Trie node need an `isEndOfWord` boolean flag?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Prefix Trees

Overview

A Trie (pronounced 'try', short for reTRIEval tree), also known as a Prefix Tree, is a specialized tree designed explicitly for storing and searching strings.

In a standard BST or HashMap, searching for a string like 'apple' takes time proportional to the number of elements in the structure. In a Trie, the search time depends ONLY on the length of the string itself (O(L)), completely independent of how many millions of words the tree holds.

A Trie stores characters in its nodes. The root is empty, and its children represent the first character of words. A path down the tree spells out a word. Because words with the same prefix (e.g., 'car', 'card', 'cart') share the same nodes for 'c', 'a', and 'r', Tries are incredibly space-efficient for dictionaries and are the ultimate data structure for autocomplete and spell-checking systems.

Syntax

Trie Node and Word Insertion
java
public class Trie {
    static class TrieNode {
        // Array of 26 pointers for lowercase English letters
        TrieNode[] children = new TrieNode[26];
        boolean isEndOfWord = false; // True if a word ends at this node
    }
    
    TrieNode root = new TrieNode();
    
    // O(L) Insertion, where L is word length
    public void insert(String word) {
        TrieNode current = root;
        
        for (char c : word.toCharArray()) {
            int index = c - 'a'; // Convert 'a'->0, 'b'->1, etc.
            
            if (current.children[index] == null) {
                current.children[index] = new TrieNode();
            }
            current = current.children[index]; // Move down the tree
        }
        current.isEndOfWord = true; // Mark the final node
    }
    
    // O(L) Search for an exact word
    public boolean search(String word) {
        TrieNode current = root;
        
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (current.children[index] == null) {
                return false; // Path breaks, word doesn't exist
            }
            current = current.children[index];
        }
        return current.isEndOfWord; // Must be marked as an end!
    }
}

Common Pitfalls

  • Assuming a matching prefix means a matching word. If you insert 'apple', the tree contains nodes for 'a-p-p-l-e'. If you search for 'app', the path exists, but 'app' is NOT a word. You must check if (current.isEndOfWord) at the final node.
  • Hardcoding array sizes poorly. Using TrieNode[26] is highly optimized but ONLY works for lowercase English letters (a-z). If you need uppercase, numbers, or symbols, you must use a HashMap<Character, TrieNode> instead, which slightly increases overhead.
  • High memory consumption for sparse datasets. If your dataset has very few shared prefixes, the Trie will create millions of objects. Each Node in Java has memory overhead, making an array-based Trie a memory hog if not carefully managed.

Interview Questions

Why use a Trie instead of a HashMap for storing a dictionary of words?

A HashMap is great for exact matches, but it cannot answer 'Give me all words starting with 'auto''. A Trie inherently groups words by their prefixes, making autocomplete searches (Prefix Matching) highly efficient. Additionally, for a dense dictionary, a Trie saves memory because common prefixes are shared.

How would you implement an Autocomplete system using a Trie?

First, traverse the Trie using the characters of the user's input prefix. Once you reach the node representing the last character of the prefix, perform a Depth-First Search (DFS) from that node downwards to collect all nodes marked isEndOfWord. These represent the autocomplete suggestions.

Real-World Example

Google's Search Bar Autocomplete is heavily reliant on distributed Trie-like structures. When you type 'how to co', the system instantly traverses to the 'o' node under 'c' under ' ' under 'o', etc., and returns the most popular paths ('how to code', 'how to cook').

example
java
public List<String> autocomplete(String prefix) {
    List<String> results = new ArrayList<>();
    TrieNode current = root;
    
    // 1. Navigate to the end of the prefix
    for (char c : prefix.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) return results; // No matches
        current = current.children[index];
    }
    
    // 2. DFS to find all words branching from here
    dfsFindWords(current, prefix, results);
    return results;
}

private void dfsFindWords(TrieNode node, String prefixSoFar, List<String> results) {
    if (node.isEndOfWord) results.add(prefixSoFar);
    
    for (int i = 0; i < 26; i++) {
        if (node.children[i] != null) {
            char nextChar = (char) (i + 'a');
            dfsFindWords(node.children[i], prefixSoFar + nextChar, results);
        }
    }
}

Check Your Knowledge

Test your understanding of Prefix Trees with these quick questions.

Question 1

What is the primary advantage of a Trie over a HashMap?

Question 2

What is the time complexity of searching for a word of length L in a Trie?

Question 3

Why does a Trie node need an `isEndOfWord` boolean flag?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A