0
0
DSA Goprogramming~3 mins

Why Trie Exists and What Hash Map Cannot Do for Strings in DSA Go - The Real Reason

Choose your learning style9 modes available
The Big Idea

What if you could find all words starting with 'app' instantly, no matter how big your list is?

The Scenario

Imagine you have a huge list of words and you want to find all words that start with a certain prefix, like "app". You try to check each word one by one to see if it starts with "app".

The Problem

Checking each word one by one is very slow when the list is large. Also, if you want to find words with similar prefixes quickly, a simple hash map can only tell if a whole word exists, but it cannot help find all words sharing the same beginning letters.

The Solution

A Trie is like a tree where each branch represents a letter. It stores words by their letters step by step. This way, you can quickly find all words that start with a prefix by just following the branches for those letters, without checking every word.

Before vs After
Before
words := []string{"apple", "app", "ape", "bat"}
for _, word := range words {
    if strings.HasPrefix(word, "app") {
        fmt.Println(word)
    }
}
After
trie := NewTrie()
trie.Insert("apple")
trie.Insert("app")
trie.Insert("ape")
trie.Insert("bat")
results := trie.StartsWith("app")
for _, word := range results {
    fmt.Println(word)
}
What It Enables

It enables lightning-fast prefix searches and autocomplete features that hash maps alone cannot provide.

Real Life Example

When you type in a search box and it suggests words as you type, it uses a Trie to quickly find all words starting with the letters you entered.

Key Takeaways

Manual search is slow for prefix queries.

Hash maps check whole words, not prefixes.

Trie stores words by letters for fast prefix lookup.