Skip to content
BytePatterns

Replace Words With Roots

MediumTries#trie#prefix-match~25m

Problem

You are given a list of root words and a sentence of space-separated words. Replace every word in the sentence that begins with one of the roots by that root. When several roots match the same word, use the shortest one. Words matching no root are left alone.

Examples

Input:  roots = ["cat", "bat", "rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Why:    each replaced word starts with a stored root
Input:  roots = ["a", "aa"], sentence = "aaa aab"
Output: "a a"
Why:    the shortest matching root wins, so "aa" never applies
Input:  roots = ["xy"], sentence = "x"
Output: "x"
Why:    edge case, the word is shorter than any root

Hints

0 / 3

Stuck on the idea rather than the code? Prefix Search covers it.