DSA · Pro · Pattern 4 of 9
Trie
10 problems.
Your progress0%
- 1st Visit
- 0/10
- 2nd Visit
- 0/10
- Revise
- 0/10
About this pattern
A trie stores strings character by character along paths from a shared root, so all words with a common prefix share the same nodes. Insertion and lookup take O(L) for a word of length L, independent of how many words are stored. Use it when a problem asks about prefixes, autocomplete, matching many words against one text or grid, or counting distinct substrings. A binary trie built over the bits of integers, from the most significant bit down, answers maximum or minimum XOR queries greedily in O(log C) each. Keep counters on nodes when elements can be removed or when you need the number of words that pass through a prefix.
struct Trie {
vector<array<int, 26>> child{array<int, 26>{}}; // node 0 is the root
vector<bool> isEnd{false};
void insert(const string& s) {
int u = 0;
for (char ch : s) {
int c = ch - 'a';
if (!child[u][c]) {
child[u][c] = child.size();
child.push_back({});
isEnd.push_back(false);
}
u = child[u][c];
}
isEnd[u] = true;
}
};