🎉 All 30 days are live — the full DSA-30 course, from Big-O to System Design. See the roadmap →
Day 18 - TriesBasic Questions

Basic Trie Questions

Five warm-ups to make the insert/walk/flag pattern automatic. Each adds one small twist to the core operations — a counter, a value, a DFS — so that by the end the practice problems feel like recombinations of moves you already know.

1. Count how many stored words have a given prefix

Add a count to each node: increment it for every node you pass through during insert. Then “how many words start with pre?” is just “walk to the pre node and read its count” — O(L).

The trick — maintain the aggregate on the way down — generalizes: store sums (Map Sum Pairs), maxima, or any associative quantity at each node.

2. Autocomplete — first k words for a prefix

Walk to the prefix node, then DFS the subtree in sorted order, stopping after k words. Covered in full on the operations page — the engine behind Search Suggestions System.

3. Longest common prefix of a set of words

Insert all words; then walk down from the root as long as there’s exactly one child and the node isn’t end-of-word. The path you walk is the LCP.

The LCP ends the moment the path branches (more than one child) or a word ends (the shortest word is itself the limit). This is the trie lens on Day 2’s Longest Common Prefix.

4. Does the trie contain any word at all?

Trivial but instructive: a trie is non-empty iff the root has children. More useful: “is this node a leaf?” (no children) tells you a word ends here with nothing after it — handy in deletion and word-break problems.

5. Count distinct substrings of a string (preview)

Insert all suffixes of a string into a trie. The number of nodes (excluding the root) equals the number of distinct substrings — because every distinct substring is a unique root-to-some-node path. O(n²) nodes naively; the optimal version uses a suffix automaton/tree, but the trie framing is the intuition.

The pattern across all five: a trie node can carry more than a boolean. A count, a value, a sum, an end-marker — whatever aggregate the problem needs, maintained incrementally during insert. Once you internalize “store the answer at the node,” half of trie problems become ‘pick the right thing to store.‘

Mini-quiz

To answer 'how many stored words start with prefix P' in O(L), what do you maintain?
Using a trie, the longest common prefix of a word set is found by walking down from the root until…

Next: Practice Questions — eight interview classics, from Implement Trie to Maximum XOR.