Replace Words
Signals to notice
Brute force first
For each word, check every root to see if it's a prefix. Repeats prefix checks redundantly. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.
The key insight
Build a trie from all roots. For each word in the sentence, walk the trie character by character — the first node marked as a word end is the shortest root. If found, replace the word with the root. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.
What must stay true
The trie naturally finds the shortest prefix match — the first end-marked node during traversal is the shortest root. No need to check all roots explicitly. As long as that statement keeps holding, you can trust the steps built on top of it.
Easy way to go wrong
Not stopping at the shortest root — if 'a' and 'app' are both roots, 'apple' should be replaced with 'a', not 'app'. The trie walk stops at the first terminal node. The fix is usually to return to the meaning of each move, not just the steps themselves.