Trie Data Structure

Back

Loading concept...

๐ŸŒณ The Magic Word Tree: Understanding Tries

Imagine you have a magical tree that can find any word super fast!


๐ŸŽฏ What is a Trie?

Think about your phoneโ€™s keyboard. When you type โ€œH-E-Lโ€, it shows โ€œHelloโ€, โ€œHelpโ€, โ€œHelicopterโ€. How does it guess so quickly?

Meet the Trie (pronounced โ€œtryโ€) โ€” a special tree that stores words letter by letter!

The Library Analogy ๐Ÿ“š

Imagine a library where books are sorted like this:

  • All books starting with โ€˜Aโ€™ go to Aisle A
  • Inside Aisle A, books with โ€˜APโ€™ go to shelf AP
  • Inside shelf AP, books with โ€˜APPโ€™ go to section APP
  • And so onโ€ฆ

Thatโ€™s exactly how a Trie works!

Finding "APPLE" in our word tree:
    (root)
      โ†“
     [A] โ†’ found 'A'!
      โ†“
     [P] โ†’ found 'P'!
      โ†“
     [P] โ†’ found 'P'!
      โ†“
     [L] โ†’ found 'L'!
      โ†“
     [E] โœ“ โ†’ found 'E'! Word complete!

๐Ÿ—๏ธ Trie Fundamentals

The Building Blocks

Every Trie has two simple parts:

1. Nodes (The Letter Boxes)

  • Each node holds ONE letter
  • Can connect to up to 26 children (a-z)
  • Has a special flag: โ€œIs this the end of a word?โ€

2. Root (The Starting Point)

  • An empty node at the top
  • Every word search begins here
  • Like the entrance door of our library

What Makes Tries Special?

Feature Why Itโ€™s Amazing
Fast Search O(m) โ€” just the word length!
Prefix Power Find all words starting with โ€œappโ€ instantly
No Collisions Unlike hash tables, no crashes
Memory Smart Words share common prefixes

A Trie Node in Java

class TrieNode {
    TrieNode[] children;
    boolean isEndOfWord;

    TrieNode() {
        children = new TrieNode[26];
        isEndOfWord = false;
    }
}

Whatโ€™s happening here?

  • children[26] โ†’ slots for a-z
  • isEndOfWord โ†’ โ€œDoes a word end here?โ€

โš™๏ธ Trie Operations

Letโ€™s learn the three magic spells to control our word tree!

๐ŸŒฑ Operation 1: INSERT (Planting Words)

The Story: Youโ€™re planting letters one by one, creating a path from root to the last letter.

void insert(String word) {
    TrieNode current = root;

    for (char c : word.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) {
            current.children[index] = new TrieNode();
        }
        current = current.children[index];
    }
    current.isEndOfWord = true;
}

Step by Step โ€” Inserting โ€œCATโ€:

Start at root (empty)
    โ†“
C: No 'C' child? Create one! Move to C.
    โ†“
A: No 'A' child? Create one! Move to A.
    โ†“
T: No 'T' child? Create one! Move to T.
    โ†“
Mark T as "End of Word" โœ“

๐Ÿ” Operation 2: SEARCH (Finding Words)

The Story: Walk down the tree letter by letter. If you reach the end AND the โ€œend of wordโ€ flag is true, you found it!

boolean search(String word) {
    TrieNode current = root;

    for (char c : word.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) {
            return false;
        }
        current = current.children[index];
    }
    return current.isEndOfWord;
}

Example โ€” Searching for โ€œCARโ€:

Start at root
    โ†“
C: Found! Move to C node.
    โ†“
A: Found! Move to A node.
    โ†“
R: NOT found! Return false โŒ

๐Ÿ”ฎ Operation 3: STARTS WITH (Prefix Check)

The Story: Same as search, but we donโ€™t care if itโ€™s a complete word. Just check if the path exists!

boolean startsWith(String prefix) {
    TrieNode current = root;

    for (char c : prefix.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) {
            return false;
        }
        current = current.children[index];
    }
    return true; // Path exists!
}

๐Ÿ”ฎ Autocomplete with Tries

This is where Tries become MAGICAL! โœจ

How Your Phone Predicts Words

When you type โ€œAPPโ€, your phone:

  1. Walks to the โ€˜Aโ€™ โ†’ โ€˜Pโ€™ โ†’ โ€˜Pโ€™ node
  2. Explores ALL paths below
  3. Collects every complete word
  4. Shows you: โ€œAppleโ€, โ€œApplyโ€, โ€œAppโ€, โ€œApplicationโ€

The Autocomplete Algorithm

List<String> autocomplete(String prefix) {
    List<String> results = new ArrayList<>();
    TrieNode current = root;

    // Step 1: Navigate to prefix
    for (char c : prefix.toCharArray()) {
        int index = c - 'a';
        if (current.children[index] == null) {
            return results; // No matches
        }
        current = current.children[index];
    }

    // Step 2: Collect all words
    findAllWords(current, prefix, results);
    return results;
}

void findAllWords(TrieNode node,
                  String prefix,
                  List<String> results) {
    if (node.isEndOfWord) {
        results.add(prefix);
    }

    for (int i = 0; i < 26; i++) {
        if (node.children[i] != null) {
            char c = (char) ('a' + i);
            findAllWords(
                node.children[i],
                prefix + c,
                results
            );
        }
    }
}

Visual Example

Words stored: cat, car, card, care, cart

Type "car":
         (root)
           โ†“
          [c]
           โ†“
          [a]
           โ†“
    โ•”โ•โ•โ•โ•โ•โ•[r]โ•โ•โ•โ•โ•โ•โ•—
    โ•‘   โ•‘   โ•‘   โ•‘   โ•‘
   [d] [e] [t] ...
    โœ“   โœ“   โœ“

Results: car, card, care, cart

๐Ÿ”Ž Word Search in Trie

Beyond simple search, Tries can solve cool puzzles!

Problem: Search with Wildcards

What if someone types โ€œc.tโ€ where โ€œ.โ€ means โ€œany letterโ€?

We should find: โ€œcatโ€, โ€œcotโ€, โ€œcutโ€!

The Solution

boolean searchWithWildcard(String word) {
    return searchHelper(word, 0, root);
}

boolean searchHelper(String word,
                     int index,
                     TrieNode node) {
    if (node == null) return false;

    if (index == word.length()) {
        return node.isEndOfWord;
    }

    char c = word.charAt(index);

    if (c == '.') {
        // Try ALL children
        for (int i = 0; i < 26; i++) {
            if (searchHelper(
                    word,
                    index + 1,
                    node.children[i])) {
                return true;
            }
        }
        return false;
    } else {
        // Normal character
        int idx = c - 'a';
        return searchHelper(
            word,
            index + 1,
            node.children[idx]
        );
    }
}

How โ€œc.tโ€ Search Works

Searching "c.t":

Step 1: c โ†’ Go to [C] node
Step 2: . โ†’ Try ALL children (a,o,u...)
Step 3: For each, check if 't' exists
         and is end of word

Found: cat โœ“, cot โœ“, cut โœ“

๐ŸŽฎ Real-World Trie Magic

Where Tries Save the Day

Application How Trie Helps
Google Search Suggestions as you type
Spell Checkers Find similar words fast
IP Routing Network address lookup
Phone Contacts Search by name prefix
DNA Matching Find gene sequences

The Complete Trie Class

class Trie {
    private TrieNode root;

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

    public void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            int i = c - 'a';
            if (node.children[i] == null) {
                node.children[i] = new TrieNode();
            }
            node = node.children[i];
        }
        node.isEndOfWord = true;
    }

    public boolean search(String word) {
        TrieNode node = findNode(word);
        return node != null && node.isEndOfWord;
    }

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

    private TrieNode findNode(String str) {
        TrieNode node = root;
        for (char c : str.toCharArray()) {
            int i = c - 'a';
            if (node.children[i] == null) {
                return null;
            }
            node = node.children[i];
        }
        return node;
    }
}

๐Ÿง  Key Takeaways

The Trie Cheat Code

๐ŸŒณ Trie = Tree for Words

๐Ÿ“ฅ INSERT: Walk + Create nodes + Mark end
๐Ÿ” SEARCH: Walk + Check end flag
๐Ÿ”ฎ PREFIX: Walk + Return true if path exists
โšก AUTOCOMPLETE: Walk to prefix + Collect all

Time Complexity Magic

Operation Time Why?
Insert O(m) m = word length
Search O(m) Just follow the path
Prefix O(m) Same as search
Autocomplete O(m + k) m=prefix, k=results

Memory Trade-off

  • Pro: Fast operations, prefix sharing
  • Con: Each node stores 26 child pointers
  • Tip: Use HashMap instead of array for sparse data

๐ŸŽฏ You Did It!

Youโ€™ve mastered the Trie data structure! ๐ŸŽ‰

What you learned:

  • โœ… What a Trie is (letter tree for words)
  • โœ… Insert, Search, and Prefix operations
  • โœ… Building autocomplete systems
  • โœ… Advanced wildcard word search

Next time you use autocomplete on your phone, youโ€™ll know the magic behind it โ€” itโ€™s a Trie! ๐ŸŒณโœจ

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.