Replace Words

In English, a **root** can be followed by other letters to form a longer word, called a **derivative**. For example, the root `"help"` followed by `"ful"` forms `"helpful"`. Given a `dictionary` of roots and a `sentence` of words separated by single spaces, replace every derivative in the sentence with the root that forms it. If a word can be formed by more than one root, use the **shortest** one. Return the sentence after the replacement.

30:00

Replace Words
medium
Free written solution
Topics
Companies

In English, a root can be followed by other letters to form a longer word, called a derivative. For example, the root "help" followed by "ful" forms "helpful".

Given a dictionary of roots and a sentence of words separated by single spaces, replace every derivative in the sentence with the root that forms it. If a word can be formed by more than one root, use the shortest one. Return the sentence after the replacement.

Example 1:
Input: {"dictionary":["cat","bat","rat"],"sentence":"the cattle was rattled by the battery"}
Output: the cat was rat by the bat
Constraints:
  • 1≤dictionary.length≤10001 \leq \text{dictionary.length} \leq 1000

  • 1≤dictionary[i].length≤1001 \leq \text{dictionary[i].length} \leq 100

  • dictionary[i] consists of only lowercase letters.

  • 1≤sentence.length≤1061 \leq \text{sentence.length} \leq 10^6

  • sentence consists of only lowercase letters and spaces.

  • The number of words in sentence is in the range [1,1000][1, 1000].

  • The length of each word in sentence is in the range [1,1000][1, 1000].

  • Every two consecutive words in sentence are separated by exactly one space, with no leading or trailing spaces.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"dictionary":["cat","bat","rat"],"sentence":"the cattle was rattled by the battery"}

Insert "cat": no edge 'c' here yet, so create it and step down.

dictionary roots

cat
bat
rat

trie (1 letter nodes)

·c

sentence

the
cattle
was
rattled
by
the
battery

output

empty

inserting a root
word walking the trie
root end mark / replaced word
missing edge
Variables
VariableValue
rootcat
word-
i-
trie_nodes1
DepthFunction Call
Stack empty
0/43