← Back to DSA Course | Chapter 16: Advanced Data Structures | Lesson 2 of 7

Trie में Insert और Search

Trie insert और search letter signs के एक path में चलने जैसा है: एक word जोड़ने के लिए आप कोई भी missing signs बनाते हैं, और इसे ढूंढने के लिए आप letters को एक-एक करके follow करते हैं।
Syntax
markup
def insert(word):
    node = root
    for ch in word:
        if ch not in node.children:
            node.children[ch] = TrieNode()
        node = node.children[ch]
    node.is_end = True

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

Insert Operation

किसी word को insert करना root से character by character चलता है, जब भी ज़रूरी character link पहले से मौजूद न हो तो एक नया child node बनाते हुए, और आखिर में पहुंची आखिरी node को एक complete word के end के रूप में मार्क करता है।

उदाहरण: Insert Operation

#include <iostream>
#include <unordered_map>
using namespace std;
struct Node { unordered_map<char,Node*> children; bool isEnd=false; };
Node* root = new Node();
void insert(string word) {
	Node* cur = root;
	for (char c : word) {
		if (!cur->children.count(c)) cur->children[c] = new Node();
		cur = cur->children[c];
	}
	cur->isEnd = true;
}
int main() { insert("cat"); cout << "'cat' inserted, new node created for each missing character link"; return 0; }
import java.util.*;
public class Main {
	static class Node { Map<Character,Node> children = new HashMap<>(); boolean isEnd = false; }
	static Node root = new Node();
	static void insert(String word) {
		Node cur = root;
		for (char c : word.toCharArray()) {
			cur.children.putIfAbsent(c, new Node());
			cur = cur.children.get(c);
		}
		cur.isEnd = true;
	}
	public static void main(String[] args) {
		insert("cat");
		System.out.println("'cat' inserted, new node created for each missing character link");
	}
}
class Node:
    def __init__(self):
        self.children = {}
        self.is_end = False
root = Node()
def insert(word):
    cur = root
    for ch in word:
        if ch not in cur.children:
            cur.children[ch] = Node()
        cur = cur.children[ch]
    cur.is_end = True
insert("cat")
print("'cat' inserted, new node created for each missing character link")
#include <stdio.h>
struct Node { struct Node* children[26]; int isEnd; };
struct Node nodes[100]; int nodeCount = 1;
void insert(char* word) {
	int cur = 0;
	for (int i = 0; word[i]; i++) {
		int idx = word[i]-'a';
		if (!nodes[cur].children[idx]) { nodes[cur].children[idx] = &nodes[nodeCount]; nodeCount++; }
	}
}
int main() {
	insert("cat");
	printf("'cat' inserted, new node created for each missing character link");
	return 0;
}

Search Operation

किसी word को search करना बिल्कुल मौजूदा links के through वही character-by-character path follow करता है; अगर बीच में कोई required link गायब हो, या final node word-end चिह्नित न हो, search सही तरीके से report करता है कि word मौजूद नहीं है।

उदाहरण: Search Operation

#include <iostream>
#include <unordered_map>
using namespace std;
struct Node { unordered_map<char,Node*> children; bool isEnd=false; };
Node* root = new Node();
bool search(string word) {
	Node* cur = root;
	for (char c : word) {
		if (!cur->children.count(c)) return false;
		cur = cur->children[c];
	}
	return cur->isEnd;
}
int main() { cout << (search("cat") ? "found" : "not found, missing link or isEnd not set"); return 0; }
import java.util.*;
public class Main {
	static class Node { Map<Character,Node> children = new HashMap<>(); boolean isEnd = false; }
	static Node root = new Node();
	static boolean search(String word) {
		Node cur = root;
		for (char c : word.toCharArray()) {
			if (!cur.children.containsKey(c)) return false;
			cur = cur.children.get(c);
		}
		return cur.isEnd;
	}
	public static void main(String[] args) {
		System.out.println(search("cat") ? "found" : "not found, missing link or isEnd not set");
	}
}
class Node:
    def __init__(self):
        self.children = {}
        self.is_end = False
root = Node()
def search(word):
    cur = root
    for ch in word:
        if ch not in cur.children:
            return False
        cur = cur.children[ch]
    return cur.is_end
print("found" if search("cat") else "not found, missing link or is_end not set")
#include <stdio.h>
struct Node { struct Node* children[26]; int isEnd; };
struct Node nodes[100]; int nodeCount = 1;
int search(char* word) {
	int cur = 0;
	for (int i = 0; word[i]; i++) {
		int idx = word[i]-'a';
		if (!nodes[cur].children[idx]) return 0;
	}
	return nodes[cur].isEnd;
}
int main() { printf(search("cat") ? "found" : "not found, missing link or isEnd not set"); return 0; }

Prefix Search

एक prefix trie में मौजूद हो सकता है — मतलब कुछ stored word इससे शुरू होता है — भले ही वह prefix खुद कभी एक complete word के रूप में insert न हुआ हो; difference बस इतना है कि पहुंची गई final node word-end चिह्नित है या नहीं।

उदाहरण: Prefix Search

#include <iostream>
using namespace std;
int main() {
	bool prefixCa_reachable = true, prefixCa_isWord = false;
	cout << "'ca' reachable=" << prefixCa_reachable << " but never inserted as a full word, isEnd=" << prefixCa_isWord;
	return 0;
}
public class Main {
	public static void main(String[] args) {
		boolean prefixReachable = true, prefixIsWord = false;
		System.out.println("'ca' reachable=" + prefixReachable + " but never inserted as a full word, isEnd=" + prefixIsWord);
	}
}
prefix_reachable, prefix_is_word = True, False
print(f"'ca' reachable={prefix_reachable} but never inserted as a full word, is_end={prefix_is_word}")
#include <stdio.h>
int main() {
	int prefixReachable = 1, prefixIsWord = 0;
	printf("'ca' reachable=%d but never inserted as a full word, isEnd=%d", prefixReachable, prefixIsWord);
	return 0;
}

Complexity

Insertion और search दोनों सिर्फ उतनी ही nodes छूते हैं जितनी word में characters हैं, इसलिए हर operation O(L) time में चलता है जहां L word की length है, trie में कितने भी दूसरे words stored हों इससे पूरी तरह independent।

उदाहरण: Complexity

#include <iostream>
using namespace std;
int main() {
	cout << "Insert and search: O(L) where L = word length, independent of how many other words are stored";
	return 0;
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Insert and search: O(L) where L = word length, independent of how many other words are stored");
	}
}
print("Insert and search: O(L) where L = word length, independent of how many other words are stored")
#include <stdio.h>
int main() {
	printf("Insert and search: O(L) where L = word length, independent of how many other words are stored");
	return 0;
}

Practical Uses

यह tries को autocomplete (एक prefix के node तक चलना, फिर इसके नीचे सब कुछ explore करना) और dictionary lookups के लिए एक natural fit बनाता है जहां आपको fast, exact membership और prefix checks चाहिए।

उदाहरण: Practical Uses

#include <iostream>
using namespace std;
int main() {
	cout << "Autocomplete: walk to a prefix's node, then explore everything beneath it";
	return 0;
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Autocomplete: walk to a prefix's node, then explore everything beneath it");
	}
}
print("Autocomplete: walk to a prefix's node, then explore everything beneath it")
#include <stdio.h>
int main() {
	printf("Autocomplete: walk to a prefix's node, then explore everything beneath it");
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक word search करना और path मौजूद होने पर true return करना, isEnd flag जांचे बिना, इसलिए prefix "ca" को एक word report किया जाता है।
  2. Insert के दौरान एक missing child node न बनाना और nullptr dereference करना।
  3. Uppercase या दूसरे characters के लिए c - a उपयोग करना, जो एक invalid index देता है।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.