Skip to content

Added Trie Data structure in Advance DSA #1233

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
149 changes: 149 additions & 0 deletions dsa/Advance/trie.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
---
id: 02-Trie
title: Introduction to Trie
sidebar_label: Trie
tags:
- dsa
- data-structures
- binary-tree
- intermediate
- javascript
- python
- c++
- java
- programming
- tutorial
sidebar_position: 2
---

# Trie Data Structure and Algorithms

## Introduction

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.

## Basic Structure

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.

### Example

```
root
/ | \
t b c
/| \ \
h o a a
/ \ \ \
e r t r

/ \ \
r k t
```

In the example above, the Trie stores the words "the", "their", "there", "bat", "cat", and "cart".

## Operations

### Insertion

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.

### Search

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.

### Deletion

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.

### Prefix Search

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.

## Applications

- **Autocomplete**: Tries are used to provide suggestions in search engines and text editors.
- **Spell Checker**: Tries store a large dictionary of words for quick lookup and suggestions.
- **IP Routing**: In networking, Tries can be used to store routing tables.
- **Genome Analysis**: Tries can store and search DNA sequences efficiently.

## Advantages and Disadvantages

### Advantages

- **Fast Lookups**: O(n) complexity for search, insertion, and deletion where n is the length of the word.
- **Prefix Search**: Efficiently find all words with a given prefix.
- **Memory Efficiency**: Space optimization for storing keys with common prefixes.

### Disadvantages

- **Space Complexity**: Requires more memory compared to some other data structures, especially for a sparse dataset.
- **Implementation Complexity**: More complex to implement than basic data structures like arrays or linked lists.

## Complexity Analysis

- **Insertion**: O(n), where n is the length of the word.
- **Search**: O(n), where n is the length of the word.
- **Deletion**: O(n), where n is the length of the word.
- **Space Complexity**: O(ALPHABET*SIZE * n \_ m), where n is the number of keys and m is the average key length.

## Example Implementation in Python

```python
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False

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

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_of_word = True

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_of_word

def delete(self, word):
def _delete(node, word, depth):
if not node:
return False
if depth == len(word):
if node.is_end_of_word:
node.is_end_of_word = False
return len(node.children) == 0
char = word[depth]
if char in node.children:
should_delete = _delete(node.children[char], word, depth + 1)
if should_delete:
del node.children[char]
return len(node.children) == 0
return False
_delete(self.root, word, 0)

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
```

## References

1. GeeksforGeeks - Trie
2. Wikipedia - Trie
3. TutorialsPoint - Trie
139 changes: 139 additions & 0 deletions dsa/Advance/trie_practice_questions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
---
id: 02-Leetcode trie Practice Questions
title: Leetcode trie Practice Questions
sidebar_label: Leetcode trie Practice Questions
tags:
- dsa
- data-structures
- binary-tree
- intermediate
- javascript
- python
- c++
- java
- programming
- tutorial
sidebar_position: 2
---

## Questions

### 1. Implement Trie (Prefix Tree)

**Problem:** Implement a trie with `insert`, `search`, and `startsWith` methods.

**Link:** [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree/)

### 2. Add and Search Word - Data structure design

**Problem:** Design a data structure that supports adding new words and finding if a string matches any previously added string.

**Link:** [Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)

### 3. Longest Word in Dictionary

**Problem:** Find the longest word in the dictionary that can be built one character at a time by other words in the dictionary.

**Link:** [Longest Word in Dictionary](https://leetcode.com/problems/longest-word-in-dictionary/)

### 4. Replace Words

**Problem:** Implement a function to replace all words in a sentence with their root forms using a dictionary of roots.

**Link:** [Replace Words](https://leetcode.com/problems/replace-words/)

### 5. Stream of Characters

**Problem:** Design a class to search for strings in a stream of characters.

**Link:** [Stream of Characters](https://leetcode.com/problems/stream-of-characters/)

### 6. Design Search Autocomplete System

**Problem:** Implement a search autocomplete system that supports inputting characters and returning the top 3 historical hot sentences.

**Link:** [Design Search Autocomplete System](https://leetcode.com/problems/design-search-autocomplete-system/)

### 7. Prefix and Suffix Search

**Problem:** Design a class that supports querying words with given prefix and suffix.

**Link:** [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/)

### 8. Word Search II

**Problem:** Given a 2D board and a list of words, find all words that can be formed by letters of the board.

**Link:** [Word Search II](https://leetcode.com/problems/word-search-ii/)

### 9. Map Sum Pairs

**Problem:** Implement a MapSum class with insert and sum methods, which sum all keys with a given prefix.

**Link:** [Map Sum Pairs](https://leetcode.com/problems/map-sum-pairs/)

### 10. Design Add and Search Words Data Structure

**Problem:** Design a data structure that supports adding new words and finding if a string matches any previously added string, with support for wildcards.

**Link:** [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure/)

### 11. Palindrome Pairs

**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.

**Link:** [Palindrome Pairs](https://leetcode.com/problems/palindrome-pairs/)

### 12. Maximum XOR of Two Numbers in an Array

**Problem:** Find the maximum XOR of two numbers in an array.

**Link:** [Maximum XOR of Two Numbers in an Array](https://leetcode.com/problems/maximum-xor-of-two-numbers-in-an-array/)

### 13. Concatenated Words

**Problem:** Find all concatenated words in a given dictionary of words.

**Link:** [Concatenated Words](https://leetcode.com/problems/concatenated-words/)

### 14. Design Phone Directory

**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.

**Link:** [Design Phone Directory](https://leetcode.com/problems/design-phone-directory/)

### 15. Search Suggestions System

**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.

**Link:** [Search Suggestions System](https://leetcode.com/problems/search-suggestions-system/)

### 16. Word Filter

**Problem:** Implement a WordFilter class that supports searching for words with a given prefix and suffix.

**Link:** [Word Filter](https://leetcode.com/problems/word-filter/)

### 17. Index Pairs of a String

**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.

**Link:** [Index Pairs of a String](https://leetcode.com/problems/index-pairs-of-a-string/)

### 18. Camelcase Matching

**Problem:** Given a list of queries and a pattern, return a list of booleans where each boolean indicates whether the query matches the pattern.

**Link:** [Camelcase Matching](https://leetcode.com/problems/camelcase-matching/)

### 19. Prefix and Suffix Search

**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).

**Link:** [Prefix and Suffix Search](https://leetcode.com/problems/prefix-and-suffix-search/)

### 20. Delete Duplicate Folders in System

**Problem:** Given a system of folders, delete all duplicate folders and return the list of unique folders.

**Link:** [Delete Duplicate Folders in System](https://leetcode.com/problems/delete-duplicate-folders-in-system/)
Loading