DEV Community

Dev Cookies
Dev Cookies

Posted on

๐ŸŒฒ Trie (Prefix Tree) Data Structure โ€“ Complete Guide with Java Code & LeetCode Questions

๐Ÿ“Œ Introduction

A Trie (pronounced "try") is a special tree-like data structure used to efficiently store and retrieve keys in a dataset of strings. It is especially useful for dictionary, autocomplete, and prefix search problems.


๐Ÿง  Why Use a Trie?

  • Fast lookup for words and prefixes.
  • Efficient storage for words with shared prefixes.
  • Great for autocomplete and spell-checking systems.

๐Ÿ”ง Trie Node Structure in Java

Each node contains:

  • A Map or array of children.
  • A boolean flag indicating if it's the end of a word.
class TrieNode {
    TrieNode[] children = new TrieNode[26];
    boolean isEndOfWord = false;

    public TrieNode() {}
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ—๏ธ Trie Implementation in Java

class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Insert word into trie
    public void insert(String word) {
        TrieNode node = root;
        for (char ch : word.toCharArray()) {
            int idx = ch - 'a';
            if (node.children[idx] == null)
                node.children[idx] = new TrieNode();
            node = node.children[idx];
        }
        node.isEndOfWord = true;
    }

    // Search full word
    public boolean search(String word) {
        TrieNode node = searchNode(word);
        return node != null && node.isEndOfWord;
    }

    // Search prefix
    public boolean startsWith(String prefix) {
        return searchNode(prefix) != null;
    }

    private TrieNode searchNode(String word) {
        TrieNode node = root;
        for (char ch : word.toCharArray()) {
            int idx = ch - 'a';
            if (node.children[idx] == null)
                return null;
            node = node.children[idx];
        }
        return node;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช Example Usage

public class Main {
    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("apple");
        System.out.println(trie.search("apple"));   // true
        System.out.println(trie.search("app"));     // false
        System.out.println(trie.startsWith("app")); // true
        trie.insert("app");
        System.out.println(trie.search("app"));     // true
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  Trie vs HashMap vs BST

Feature Trie HashMap BST
Time Complexity O(L) O(1) avg O(log N)
Space Efficiency Medium-High Low Medium
Prefix Search โœ… Efficient โŒ Inefficient โŒ Inefficient
Use Case Dictionary, Autocomplete Key-Value Store Sorted Data

๐Ÿ’ก Real-Life Use Cases

  • Autocomplete engines (Google search).
  • Spell-checkers.
  • IP routing (Longest Prefix Match).
  • Word games like Boggle or Scrabble.

๐Ÿ”ฅ Top LeetCode Problems on Trie

Problem Description Link
208. Implement Trie (Prefix Tree) Basic Trie operations ๐Ÿ”— LeetCode
211. Design Add and Search Words Data Structure Supports wildcard search ๐Ÿ”— LeetCode
212. Word Search II Search words in 2D grid using Trie + DFS ๐Ÿ”— LeetCode
648. Replace Words Replace words in sentence using Trie dictionary ๐Ÿ”— LeetCode
720. Longest Word in Dictionary Longest word built one char at a time ๐Ÿ”— LeetCode
676. Implement Magic Dictionary Similar to word search with wildcard ๐Ÿ”— LeetCode
1268. Search Suggestions System Auto-suggestions using Trie ๐Ÿ”— LeetCode
745. Prefix and Suffix Search Complex prefix+suffix queries ๐Ÿ”— LeetCode

โš™๏ธ Time and Space Complexity

Operation Time Complexity Space Complexity
Insert O(L) O(26 ร— L ร— N)
Search O(L) O(1)
Prefix Match O(L) O(1)

L = length of the word, N = number of words


๐Ÿ“š Advanced Variants

  • Compressed Trie / Radix Tree โ€“ optimized for memory.
  • Ternary Search Tree โ€“ space-efficient Trie.
  • DAWG (Directed Acyclic Word Graph) โ€“ minimized form of Trie.

โœ๏ธ Final Thoughts

Trie is one of the most powerful data structures when dealing with words and prefixes. While it may consume more space than HashMaps or Sets, it provides unmatched efficiency in problems involving prefixes, auto-completion, and pattern matching.

Top comments (1)