Problem

In English, we have a concept called root, which can be followed by some other word to form another longer word - let’s call this word derivative. For example, when the root "help" is followed by the word "ful", we can form a derivative "helpful".

Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the derivatives in the sentence with the root forming it. If a derivative can be replaced by more than one root, replace it with the root that has the shortest length.

Return the sentence after the replacement.

Examples

Example 1:

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

Example 2:

Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"

Solution

Method 1 - Using the trie

We can follow these steps:

  1. Construct the trie: Create the trie with the dictionary
  2. Now, we split the sentence into words
  3. Then, for each word we try to find the shortest matching prefix. For eg. if trie has “cattle123”, and word is “cattle” then we return “”, but if trie has “cattle123” and word is “cattle1234”, then we return “cattle123”.

Code

Java
class Solution {
    public String replaceWords(List<String> dictionary, String sentence) {
        Trie root = new Trie();
        dictionary.forEach(root::insert);
        String[] words = sentence.split(" ");
        
         return Arrays.stream(words)
                 .map(word -> {
                     String prefix = root.shortestMatchingPrefix(word);
                     return prefix.isEmpty() ? word : prefix;
                 })
                 .collect(Collectors.joining(" "));  // Join the transformed words with spaces
    }
    
}

Complexity

  • ⏰ Time complexity: O(n*l) for insert operation in the trie, where is number of words in dictionary, and l is the average length of those words. For searching the word prefix, it takes O(m*l), where is m is number of words in sentence, and for each word, we go average depth l when trying to find the prefix. So, it will be O((n+m)*l)
  • 🧺 Space complexity: O(n*l)