Skip to content
We areTOP 1%
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;
    }
};

Problems

Trie questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Implement Trie (Prefix Tree)LeetCodeMedium Solve Implement Trie (Prefix Tree) on LeetCode (opens in a new tab)
2Longest Word in DictionaryLeetCodeMedium Solve Longest Word in Dictionary on LeetCode (opens in a new tab)
3Design Add and Search Words Data StructureLeetCodeMedium Solve Design Add and Search Words Data Structure on LeetCode (opens in a new tab)
4Maximum XOR of Two Numbers in an ArrayLeetCodeMedium Solve Maximum XOR of Two Numbers in an Array on LeetCode (opens in a new tab)
5Polycarp's phone bookCodeforcesMedium 1600Solve Polycarp's phone book on Codeforces (opens in a new tab)
6Good SubstringsCodeforcesHard 1800Solve Good Substrings on Codeforces (opens in a new tab)
7Vasiliy's MultisetCodeforcesHard 1800Solve Vasiliy's Multiset on Codeforces (opens in a new tab)
8Perfect SecurityCodeforcesHard 1800Solve Perfect Security on Codeforces (opens in a new tab)
9Maximum XOR With an Element From ArrayLeetCodeHard Solve Maximum XOR With an Element From Array on LeetCode (opens in a new tab)
10Word Search IILeetCodeHard Solve Word Search II on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account