</>
Skip to content
DSA lessons (53/55)

DSA — Trie

What is a Trie?

A tree-like data structure for storing strings, where each node represents a character.

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_end = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

Insert

def insert(self, word):
    node = self.root
    for char in word:
        if char not in node.children:
            node.children[char] = TrieNode()
        node = node.children[char]
    node.is_end = True

Search

def search(self, word):
    node = self.root
    for char in word:
        if char not in node.children:
            return False
        node = node.children[char]
    return node.is_end

Starts With

def starts_with(self, prefix):
    node = self.root
    for char in prefix:
        if char not in node.children:
            return False
        node = node.children[char]
    return True

Applications

ApplicationDescription
AutocompleteWord suggestions
Spell checkingValid word lookup
IP routingLongest prefix match
Word gamesScrabble, Boggle

Mini Practice

  1. Implement a trie
  2. Search for words
  3. Find all words with prefix
  4. Auto-complete feature

Up Next

Continue with Segment Tree — range query data structure.

Related Topics

Frequently Asked Questions about Trie

What is Trie in DSA?

Trie is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Trie?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Trie.

Why is Trie important in DSA?

Trie is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.