We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium 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 →Build a trie of the roots, marking terminal nodes. Then for each word, walk down from the root one character at a time and stop the moment you stand on a marked node - emitting the characters consumed so far.
That early stop is the entire solution to the "shortest root" requirement. Because you descend in increasing length order, the first marker you meet is necessarily the shortest matching root, so `["catt", "cat"]` against `cattle` yields `cat` without any comparison of candidate lengths. Sorting the dictionary or collecting all matches and taking the minimum is wasted work.
If the walk falls off the trie (no child for the next character) without ever hitting a marker, no root is a prefix of this word, so it passes through untouched.
Compared with checking every root against every word - O(words x roots x length) - the trie makes each word cost only its own length.
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.