---
Difficulty: Medium
Source: 160 Days of Problem Solving
Tags:
- Trie
- Design-Pattern
- Advanced Data Structure
---
# 🚀 _Day 1. Implement Trie_ 🧠
The problem can be found at the following link: [Question Link](https://www.geeksforgeeks.org/batch/gfg-160-problems/track/tries-gfg-160/problem/trie-insert-and-search0651)
## 💡 **Problem Description:**
Implement the Trie data structure. You are given queries of the following three types:
- **Type 1**: Insert a word into the Trie.
- **Type 2**: Search whether a word exists in the Trie.
- **Type 3**: Check whether a word is a prefix of any word stored in the Trie.
> 📅 Note: Sorry for uploading late, my Final Sem exam is going on.
## 🔍 **Example Walkthrough:**
### **Example 1:**
#### **Input:**
`[[1, "abcd"], [1, "abc"], [1, "bcd"], [2, "bc"], [3, "bc"], [2, "abc"]]`
#### **Output:**
`[false, true, true]`
#### **Explanation:**
- "bc" does not exist as a word
- "bc" exists as prefix of "bcd"
- "abc" exists
### **Example 2:**
#### **Input:**
`[[1, "gfg"], [1, "geeks"], [3, "fg"], [3, "geek"], [2, "for"]]`
#### **Output:**
`[false, true, false]`
#### **Explanation:**
- "fg" is not a prefix
- "geek" is a prefix of "geeks"
- "for" not in Trie
### **Constraints:**
- $1 \leq \text{query.size()} \leq 10^4$
- $1 \leq \text{word.size()} \leq 10^3$
## 🎯 **My Approach:**
### **Fixed-Size Trie Using 26 Pointers**
### **Algorithm Steps:**
We create a class Trie, with a nested structure (Node) that stores a boolean flag for end of word and a fixed array of 26 pointers (one for each lowercase letter).
- **Insert:** Walk through characters, initialize child if needed.
- **Search:** Check for existence and end-of-word.
- **Prefix:** Just ensure prefix exists in Trie.
## 🕒 **Time and Auxiliary Space Complexity**
- **Expected Time Complexity:** O(L), where L = length of the word
- **Expected Auxiliary Space Complexity:** O(1), as each function uses constant extra space aside from Trie structure itself
## 📝 **Solution Code**
## **Code (C++)**
```cpp
// ✅ Fixed‐Array Trie (26 pointers per node)
class Trie {
struct N { N* c[26] = {}; bool e = 0; }*r = new N;
public:
void insert(string &w) {
auto n = r;
for (char ch : w) n = n->c[ch - 'a'] ?: (n->c[ch - 'a'] = new N);
n->e = 1;
}
bool search(string &w) {
auto n = r;
for (char ch : w) if (!(n = n->c[ch - 'a'])) return 0;
return n->e;
}
bool isPrefix(string &w) {
auto n = r;
for (char ch : w) if (!(n = n->c[ch - 'a'])) return 0;
return 1;
}
};
```
## 📊 **2️⃣ Map‐Based Trie (unordered_map children)**
#### **Algorithm Steps:**
1. Each node stores an `unordered_map⚡ Alternative Approaches