LeetCode 648 Replace Words - Why Naive Fails

The trap

For each word, check every root to see if the word starts with it. Keep the shortest matching root.

With dd roots and ww words, each of average length mm, checking all combinations is O(dwm)O(d \cdot w \cdot m).

For large dictionaries and sentences, this is slow. Can you find the shortest root faster?