Skip to content

Commit 130cfe6

Browse files
Added Trie Data structure in Advance DSA
1 parent 4f16aa4 commit 130cfe6

File tree

2 files changed

+288
-0
lines changed

2 files changed

+288
-0
lines changed

dsa/Advance/trie.md

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
---
2+
id: 02-Trie
3+
title: Introduction to Trie
4+
sidebar_label: Trie
5+
tags:
6+
- dsa
7+
- data-structures
8+
- binary-tree
9+
- intermediate
10+
- javascript
11+
- python
12+
- c++
13+
- java
14+
- programming
15+
- tutorial
16+
sidebar_position: 2
17+
---
18+
19+
# Trie Data Structure and Algorithms
20+
21+
## Introduction
22+
23+
A Trie, also known as a prefix tree, is a type of search tree that is used to store a dynamic set of strings. The name "Trie" comes from the word "retrieval" as they are used to retrieve a key in a dataset of strings. Tries are particularly useful for tasks involving a large set of strings, such as dictionary words or contact lists.
24+
25+
## Basic Structure
26+
27+
A Trie is a tree-like data structure where each node represents a single character of a string. The root node is associated with an empty string. Each subsequent node represents the next character of the inserted string. Nodes that share a common prefix share the same path from the root.
28+
29+
### Example
30+
31+
```
32+
root
33+
/ | \
34+
t b c
35+
/| \ \
36+
h o a a
37+
/ \ \ \
38+
e r t r
39+
40+
/ \ \
41+
r k t
42+
```
43+
44+
In the example above, the Trie stores the words "the", "their", "there", "bat", "cat", and "cart".
45+
46+
## Operations
47+
48+
### Insertion
49+
50+
To insert a word into a Trie, we start at the root node and follow the path corresponding to the characters in the word. If a node for a character does not exist, we create a new node. After inserting all characters, we mark the last node as the end of a word.
51+
52+
### Search
53+
54+
To search for a word in a Trie, we follow the path corresponding to the characters in the word starting from the root. If we can follow the path for all characters and reach a node marked as the end of a word, the word exists in the Trie.
55+
56+
### Deletion
57+
58+
To delete a word from a Trie, we first ensure the word exists. If it does, we remove the nodes corresponding to the word's characters, starting from the last character and moving towards the root. If removing a node would break the path for another word, we stop the deletion process for that node.
59+
60+
### Prefix Search
61+
62+
A Trie can efficiently find all words with a given prefix. By following the path corresponding to the prefix characters, we can reach a node where all the sub-nodes form words with the given prefix.
63+
64+
## Applications
65+
66+
- **Autocomplete**: Tries are used to provide suggestions in search engines and text editors.
67+
- **Spell Checker**: Tries store a large dictionary of words for quick lookup and suggestions.
68+
- **IP Routing**: In networking, Tries can be used to store routing tables.
69+
- **Genome Analysis**: Tries can store and search DNA sequences efficiently.
70+
71+
## Advantages and Disadvantages
72+
73+
### Advantages
74+
75+
- **Fast Lookups**: O(n) complexity for search, insertion, and deletion where n is the length of the word.
76+
- **Prefix Search**: Efficiently find all words with a given prefix.
77+
- **Memory Efficiency**: Space optimization for storing keys with common prefixes.
78+
79+
### Disadvantages
80+
81+
- **Space Complexity**: Requires more memory compared to some other data structures, especially for a sparse dataset.
82+
- **Implementation Complexity**: More complex to implement than basic data structures like arrays or linked lists.
83+
84+
## Complexity Analysis
85+
86+
- **Insertion**: O(n), where n is the length of the word.
87+
- **Search**: O(n), where n is the length of the word.
88+
- **Deletion**: O(n), where n is the length of the word.
89+
- **Space Complexity**: O(ALPHABET*SIZE * n \_ m), where n is the number of keys and m is the average key length.
90+
91+
## Example Implementation in Python
92+
93+
```python
94+
class TrieNode:
95+
def __init__(self):
96+
self.children = {}
97+
self.is_end_of_word = False
98+
99+
class Trie:
100+
def __init__(self):
101+
self.root = TrieNode()
102+
103+
def insert(self, word):
104+
node = self.root
105+
for char in word:
106+
if char not in node.children:
107+
node.children[char] = TrieNode()
108+
node = node.children[char]
109+
node.is_end_of_word = True
110+
111+
def search(self, word):
112+
node = self.root
113+
for char in word:
114+
if char not in node.children:
115+
return False
116+
node = node.children[char]
117+
return node.is_end_of_word
118+
119+
def delete(self, word):
120+
def _delete(node, word, depth):
121+
if not node:
122+
return False
123+
if depth == len(word):
124+
if node.is_end_of_word:
125+
node.is_end_of_word = False
126+
return len(node.children) == 0
127+
char = word[depth]
128+
if char in node.children:
129+
should_delete = _delete(node.children[char], word, depth + 1)
130+
if should_delete:
131+
del node.children[char]
132+
return len(node.children) == 0
133+
return False
134+
_delete(self.root, word, 0)
135+
136+
def starts_with(self, prefix):
137+
node = self.root
138+
for char in prefix:
139+
if char not in node.children:
140+
return False
141+
node = node.children[char]
142+
return True
143+
```
144+
145+
## References
146+
147+
1. GeeksforGeeks - Trie
148+
2. Wikipedia - Trie
149+
3. TutorialsPoint - Trie
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
---
2+
id: 02-Leetcode trie Practice Questions
3+
title: Leetcode trie Practice Questions
4+
sidebar_label: Leetcode trie Practice Questions
5+
tags:
6+
- dsa
7+
- data-structures
8+
- binary-tree
9+
- intermediate
10+
- javascript
11+
- python
12+
- c++
13+
- java
14+
- programming
15+
- tutorial
16+
sidebar_position: 2
17+
---
18+
19+
## Questions
20+
21+
### 1. Implement Trie (Prefix Tree)
22+
23+
**Problem:** Implement a trie with `insert`, `search`, and `startsWith` methods.
24+
25+
**Link:** [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)
26+
27+
### 2. Add and Search Word - Data structure design
28+
29+
**Problem:** Design a data structure that supports adding new words and finding if a string matches any previously added string.
30+
31+
**Link:** [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)
32+
33+
### 3. Longest Word in Dictionary
34+
35+
**Problem:** Find the longest word in the dictionary that can be built one character at a time by other words in the dictionary.
36+
37+
**Link:** [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/)
38+
39+
### 4. Replace Words
40+
41+
**Problem:** Implement a function to replace all words in a sentence with their root forms using a dictionary of roots.
42+
43+
**Link:** [Replace Words](https://leetcode.com/problems/replace-words/)
44+
45+
### 5. Stream of Characters
46+
47+
**Problem:** Design a class to search for strings in a stream of characters.
48+
49+
**Link:** [Stream of Characters](https://leetcode.com/problems/stream-of-characters/)
50+
51+
### 6. Design Search Autocomplete System
52+
53+
**Problem:** Implement a search autocomplete system that supports inputting characters and returning the top 3 historical hot sentences.
54+
55+
**Link:** [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/)
56+
57+
### 7. Prefix and Suffix Search
58+
59+
**Problem:** Design a class that supports querying words with given prefix and suffix.
60+
61+
**Link:** [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/)
62+
63+
### 8. Word Search II
64+
65+
**Problem:** Given a 2D board and a list of words, find all words that can be formed by letters of the board.
66+
67+
**Link:** [Word Search II](https://leetcode.com/problems/word-search-ii/)
68+
69+
### 9. Map Sum Pairs
70+
71+
**Problem:** Implement a MapSum class with insert and sum methods, which sum all keys with a given prefix.
72+
73+
**Link:** [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/)
74+
75+
### 10. Design Add and Search Words Data Structure
76+
77+
**Problem:** Design a data structure that supports adding new words and finding if a string matches any previously added string, with support for wildcards.
78+
79+
**Link:** [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/)
80+
81+
### 11. Palindrome Pairs
82+
83+
**Problem:** Given a list of unique words, find all pairs of distinct indices (i, j) such that the concatenation of words[i] and words[j] is a palindrome.
84+
85+
**Link:** [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/)
86+
87+
### 12. Maximum XOR of Two Numbers in an Array
88+
89+
**Problem:** Find the maximum XOR of two numbers in an array.
90+
91+
**Link:** [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/)
92+
93+
### 13. Concatenated Words
94+
95+
**Problem:** Find all concatenated words in a given dictionary of words.
96+
97+
**Link:** [Concatenated Words](https://leetcode.com/problems/concatenated-words/)
98+
99+
### 14. Design Phone Directory
100+
101+
**Problem:** Design a phone directory that initially has all phone numbers available to be assigned and supports checking availability, getting a number, and releasing a number.
102+
103+
**Link:** [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/)
104+
105+
### 15. Search Suggestions System
106+
107+
**Problem:** Given an array of products and a search word, design a system that suggests at most 3 products as you type each character of the search word.
108+
109+
**Link:** [Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/)
110+
111+
### 16. Word Filter
112+
113+
**Problem:** Implement a WordFilter class that supports searching for words with a given prefix and suffix.
114+
115+
**Link:** [Word Filter](https://leetcode.com/problems/word-filter/)
116+
117+
### 17. Index Pairs of a String
118+
119+
**Problem:** Given a string text and an array of words, return all index pairs [i, j] so that the substring text[i...j] is in the array of words.
120+
121+
**Link:** [Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string/)
122+
123+
### 18. Camelcase Matching
124+
125+
**Problem:** Given a list of queries and a pattern, return a list of booleans where each boolean indicates whether the query matches the pattern.
126+
127+
**Link:** [Camelcase Matching](https://leetcode.com/problems/camelcase-matching/)
128+
129+
### 19. Prefix and Suffix Search
130+
131+
**Problem:** Implement a class that supports querying words with a given prefix and suffix (similar to question 7 but can be a different version or extension).
132+
133+
**Link:** [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/)
134+
135+
### 20. Delete Duplicate Folders in System
136+
137+
**Problem:** Given a system of folders, delete all duplicate folders and return the list of unique folders.
138+
139+
**Link:** [Delete Duplicate Folders in System](https://leetcode.com/problems/delete-duplicate-folders-in-system/)

0 commit comments

Comments
 (0)