templates/trie.cpp
compilable
$cat templates/trie
Trie
Prefix tree for string storage with insert, search, prefix check, and erase in O(|s|).
#trie#prefix-tree#string#dictionary
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
#include <bits/stdc++.h>
using namespace std;
const int ALPHA = 26;
struct Trie {
struct Node {
int ch[ALPHA];
int freq;
bool isEnd;
};
vector<Node> t;
Trie() { t.push_back({{}, 0, false}); }
int newNode() { t.push_back({{}, 0, false}); return t.size() - 1; }
void insert(const string& s) {
int cur = 0;
for (char c : s) {
int idx = c - 'a';
if (!t[cur].ch[idx]) t[cur].ch[idx] = newNode();
cur = t[cur].ch[idx];
t[cur].freq++;
}
t[cur].isEnd = true;
}
bool search(const string& s) {
int cur = 0;
for (char c : s) {
int idx = c - 'a';
if (!t[cur].ch[idx]) return false;
cur = t[cur].ch[idx];
}
return t[cur].isEnd;
}
bool startsWith(const string& s) {
int cur = 0;
for (char c : s) {
int idx = c - 'a';
if (!t[cur].ch[idx]) return false;
cur = t[cur].ch[idx];
}
return true;
}
void erase(const string& s) {
if (!search(s)) return;
int cur = 0;
for (char c : s) {
int idx = c - 'a';
int nxt = t[cur].ch[idx];
t[nxt].freq--;
if (t[nxt].freq == 0) { t[cur].ch[idx] = 0; return; }
cur = nxt;
}
t[cur].isEnd = false;
}
int countPrefix(const string& s) {
int cur = 0;
for (char c : s) {
int idx = c - 'a';
if (!t[cur].ch[idx]) return 0;
cur = t[cur].ch[idx];
}
return t[cur].freq;
}
};72 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Trie (Prefix Tree)
Stores strings character by character. Each node has up to children and a word-end flag.
Operations
insert(s) — add string to triesearch(s) — check if exact string existsstartsWith(s) — check if any string has prefix erase(s) — remove string, pruning dead branchesHow It Works
children[26], isEnd flag, and freq counterfreqfreq and deletes nodes that reach zeroWhen to Use
Notes
ALPHA and offset for uppercase ('A') or digits ('0')