Dodomeki
Sign in

112. The Shortest Root

Medium

A search system receives a dictionary of roots and a sentence. For each word in the sentence, replace it with the shortest root that is a prefix of that word, if one exists. If no root is a prefix of the word, leave it unchanged. The sentence contains words made only of lowercase letters, separated by a single space. Return the resulting sentence, keeping the words in order and separating them with a single space.

Example 1
Input: raizes = ["sol", "so", "mar"], frase = "somente solitario marcacao"
Output: "so so mar"
Explanation: The root "so" is the shortest matching prefix of both "somente" and "solitario".
Example 2
Input: raizes = ["casa", "luz"], frase = "casamento iluminar barco"
Output: "casa iluminar barco"
Explanation: "casamento" starts with "casa"; the other words have no matching root.
Example 3
Input: raizes = ["ab", "abc"], frase = "abc abelha"
Output: "ab ab"
Explanation: For each word, the shortest matching prefix root is "ab".
Constraints
  • 1 <= raizes.length <= 10^4
  • 1 <= raizes[i].length <= 100
  • 1 <= frase.length <= 10^5
  • Each word in frase contains only lowercase letters and has a length between 1 and 100.
  • Words in frase are separated by a single space.
TrieStrings
Caso 1
raizes =
["sol","so","mar"]
frase =
"somente solitario marcacao"
Expected =
"so so mar"
Caso 2
raizes =
["casa","luz"]
frase =
"casamento iluminar barco"
Expected =
"casa iluminar barco"
Caso 3
raizes =
["ab","abc"]
frase =
"abc abelha"
Expected =
"ab ab"

Run checks these 3 cases. Submit runs all 12, including hidden ones.