3.4.14 · HinglishTrees

Trie (prefix tree) — insert, search, startsWith, applications (autocomplete, spell check)

2,083 words9 min readRead in English

3.4.14 · Coding › Trees


Trie KYA hota hai?

Ek node typically yeh store karta hai:

class TrieNode:
    children: map<char, TrieNode>   # up to 26 for lowercase a–z
    isEnd: bool                     # does a word END here?
Figure — Trie (prefix tree) — insert, search, startsWith, applications (autocomplete, spell check)

Teen core operations KAISE kaam karte hain

Teeno character by character root se chalte hain. Fark sirf yeh hai ki end mein kya check karte hain.

1. insert(word)

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

2. search(word) — kya POORA word present hai?

def search(self, word):
    node = self.root
    for c in word:
        if c not in node.children:
            return False
        node = node.children[c]
    return node.isEnd      # NOTE: not just True

3. startsWith(prefix) — kya KISI word ka yeh prefix hai?

def startsWith(self, prefix):
    node = self.root
    for c in prefix:
        if c not in node.children:
            return False
        node = node.children[c]
    return True            # path exists ⇒ prefix exists

Complexity (derive karo, memorize mat karo)

Maano = query/word ki length, = words ki sankhya, = alphabet size.


Worked Examples


Applications (WHY yeh matter karta hai)

def autocomplete(self, prefix):
    node = self.root
    for c in prefix:
        if c not in node.children: return []
        node = node.children[c]
    res = []
    def dfs(n, path):
        if n.isEnd: res.append(prefix + path)
        for c, child in n.children.items():
            dfs(child, path + c)
    dfs(node, "")
    return res

Doosre uses: IP routing (longest-prefix match), T9 / phone keypads, word games (Boggle solver dead prefixes jaldi prune karta hai), DNA substring search.


Common Mistakes (Steel-manned)


Recall Feynman: 12-saal ke bacche ko samjhao

Ek giant treasure map socho jo tree jaisi shaped hai. Koi word spell karne ke liye tum letters ke saath chalte ho: trunk se shuru karo, branch c par kadam rakho, phir a, phir r — ab tumne "car" spell kar liya. Agar kisi ne exactly wahan treasure (ek chota ✅ flag) gada hai jahan tum khade ho, toh "car" ek real word hai! Jo words same se shuru hote hain woh split hone se pehle same branches par chalte hain, toh map mein c-a-r kabhi repeat nahi hota. "ca" se shuru hone wale saare words chahiye? Bas ca tak chalo aur apne upar har branch explore karo — yahi autocomplete hai!


Active Recall

Har trie node kya store karta hai?
Child characters → child nodes ka ek map, plus ek isEnd boolean jo mark karta hai ki koi word wahan khatam hoti hai ya nahi.
Trie mein "leaf = word" kyun kaam nahi karta?
car jaisi word internal ho sakti hai (uska child d hai card ke liye) phir bhi ek valid word hai, isliye humein ek explicit isEnd flag chahiye.
search aur startsWith mein code ka SIRF kya fark hai?
search return node.isEnd se khatam hota hai; startsWith return True se khatam hota hai (path existence kaafi hai).
insert/search/startsWith ki time complexity?
jahan word ki length hai — stored words ki sankhya se independent.
Trie ka root node kya represent karta hai?
Empty string "".
Autocomplete trie ko kaise use karta hai?
Prefix node tak walk karo, phir subtree ka DFS karo aur isEnd=True wale saare nodes collect karo, prefix prepend karte hue.
Sirf "car" containing trie par search("ca") kya return karta hai?
False — path exist karta hai lekin koi word a par khatam nahi hoti (a.isEnd False hai).
Usi trie par startsWith("ca") kya return karta hai?
True — path c→a exist karta hai.
Prefix queries ke liye trie hash set se better kyun hai?
Hash set mein koi shared-prefix structure nahi hoti; trie saare words ko common prefix ke hisaab se group karta hai isliye prefix queries sirf relevant subtree explore karti hain.
Trie se koi word safely kaise delete karte hain?
Uske end node ka isEnd unset karo; nodes ko upar se sirf tab prune karo jab unka koi child nahi aur woh kisi aur word ka end nahi hain.

Connections

  • Hash Table — fast exact lookup, lekin koi prefix structure nahi.
  • Binary Search Tree — string ops mein vs trie ka .
  • DFS — trie subtree mein completions collect karne ke liye use hota hai.
  • Suffix Tree / Radix Tree (Compressed Trie) — space-optimized relatives.
  • Edit Distance — spell-check suggestion generation.
  • Longest Prefix Match — IP routing application.

Concept Map

lacks

motivates

root is

each edge is

each node is

marked by

distinguishes

supports

supports

supports

creates missing children then

walks path then checks

walks path, ignores

enables

Hash set

Shared prefix info

Trie prefix tree

Empty string

One character

Prefix on path

isEnd flag

Word vs prefix

insert word

search word

startsWith prefix

Autocomplete and spell check