Replace Words LeetCode Solution

Last updated on February 9th, 2025 at 07:10 am

Here, we see the Replace Words LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Hash Table, Trie

Companies

Uber

Level of Question

Medium

Replace Words LeetCode Solution

Replace Words LeetCode Solution

1. Problem Statement

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 successor. For example, when the root “an” is followed by the successor word “other”, we can form a new word “another”.

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

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”

Example 2:
Input: dictionary = [“a”,”b”,”c”], sentence = “aadsfasf absbs bbab cadsfafs”
Output: “a a b c”

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “Prefix Matching”, where we need to replace words or find the shortest prefix match for a given word. The goal is to replace words in a sentence with their shortest prefix from a dictionary.

3. Code Implementation in Different Languages

3.1 Replace Words C++

class Solution {
public:
    string replaceWords(vector<string>& dictionary, string sentence) {
        string ans="";
        unordered_set<string>s(dictionary.begin(),dictionary.end());
        string x="";
        for(int i=0;i<sentence.size();)
        {
            if(sentence[i]==' ')
            {
                ans+=x;
                ans+=' ';
                x="";
            }
            else
            {
                x+=sentence[i];
                if(s.find(x)!=s.end())
                {
                    while(i<sentence.size() && sentence[i]!=' ')
                    {
                        i++;
                    }
                    ans+=x;
                    
                    x="";
                    continue;
                }
            }
            i++;
        }
        if(x.size()!=0)ans+=x;
        return ans;
    }
};

3.2 Replace Words Java

class Solution {
    public String replaceWords(List<String> dictionary, String sentence) {
        Set<String> set = new HashSet();
        for (String root: dictionary) 
            set.add(root);
        StringBuilder ans = new StringBuilder();
        String word[] = sentence.split(" ");
        for (int j=0;j<word.length;j++) {
            String prefix = "";
            for (int i=1; i<=word[j].length();++i) {
                prefix = word[j].substring(0, i);
                if (set.contains(prefix)) 
                    break;
            }
            if(ans.length()>0) 
                ans.append(" ");
            ans.append(prefix);
        }
        return ans.toString();
    }
}

3.3 Replace Words JavaScript

var replaceWords = function(dictionary, sentence) {
    let wordArr = sentence.split(" ");
    wordArr = wordArr.map(w => {
        for(let i = 0; i <= dictionary.length - 1; i++) {
            if (w.indexOf(dictionary[i]) === 0) {
                w = dictionary[i];
            }
        }
        return w;
    })
    return wordArr.reduce((str, word) => str += `${word} `, "").trim();
};

3.4 Replace Words Python

class Solution(object):
    def replaceWords(self, dictionary, sentence):
        setenceAsList = sentence.split(" ")
        for i in range(len(setenceAsList)):
            for j in dictionary:
                if setenceAsList[i].startswith(j):
                    setenceAsList[i] = j
        return " ".join(setenceAsList)

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n * m + k)O(k + n)
JavaO(n * m + k)O(k + n)
JavaScriptO(n * m * k)O(n)
PythonO(n * m * k)O(n)

Here,
m = avg word length
n = number of words in the sentence
k = dictionary size

  • The C++ and Java implementations are more efficient due to the use of hash-based data structures (unordered_set and HashSet) for prefix lookups.
  • The JavaScript and Python implementations are less efficient because they iterate through the dictionary for each word in the sentence, leading to an additional factor of k in the time complexity.
  • All implementations have similar space complexity, dominated by the size of the result string and the dictionary storage (if applicable).
Scroll to Top