We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy trie problem, graded against 6 test cases (3 of them hidden).
A prefix tree for fast string lookup by shared prefix.
Reach for it when you see: Many words, repeated prefix queries, autocomplete, or word-search over a grid.
More Trieproblems →A trie stores words as a character tree, so all words sharing a prefix share the path that spells it. The trick here is what each node holds: not "is this the end of a word" but how many words pass through this node.
On insert, bump that counter at every node along the path. Then a prefix query is just a walk: follow the prefix's characters from the root, and the counter at the node you land on is the answer - already computed, no subtree traversal needed. Falling off the trie means no word has that prefix, so the answer is 0.
The cost model is what makes this worth learning. The naive nested scan is O(P x W x L). The trie pays O(total characters) once to build, then O(prefix length) per query - independent of how many words there are. With 10^4 words and 10^4 prefixes that is the difference between hundreds of millions of character comparisons and a few hundred thousand.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.