Leetcode 648: Replace Words

grid47
grid47
Exploring patterns and algorithms
Sep 3, 2024 8 min read

A string where words are replaced with their corresponding replacements, glowing softly as replacements are made.
Solution to LeetCode 648: Replace Words Problem

In English, certain words can be formed by adding a suffix to a root word. Given a list of root words and a sentence, replace every word in the sentence that is a derivative of any root word with the shortest root. If a word can be formed by more than one root, replace it with the shortest root.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of root words (dictionary) and a sentence, both represented as strings.
Example: dictionary = ["dog", "cat", "rat"], sentence = "the dogs were caught by the rats"
Constraints:
• 1 <= dictionary.length <= 1000
• 1 <= dictionary[i].length <= 100
• dictionary[i] consists of only lowercase letters.
• 1 <= sentence.length <= 10^6
• sentence consists of only lowercase letters and spaces.
• The number of words in sentence is in the range [1, 1000].
• Each word in sentence has a length in the range [1, 1000].
• There are no leading or trailing spaces in the sentence.
Output: The output should be a sentence with all derivative words replaced by the shortest corresponding root word.
Example: the dog were caught by the rat
Constraints:
• The output will be a string with words separated by spaces, and no leading or trailing spaces.
Goal: Replace each word in the sentence with the shortest root word it can be derived from.
Steps:
• 1. Build a Trie data structure to store all root words.
• 2. For each word in the sentence, attempt to find the shortest prefix that exists in the Trie.
• 3. Replace the word with its root if a match is found.
Goal: The input and output should be handled efficiently due to the large size constraints.
Steps:
• The solution must handle up to 1000 root words and a sentence of length up to 10^6 efficiently.
Assumptions:
• The dictionary is non-empty.
• The sentence contains words that are potentially derivatives of roots.
Input: dictionary = ["dog", "cat", "rat"], sentence = "the dogs were caught by the rats"
Explanation: The words 'dogs' and 'rats' are derivatives of 'dog' and 'rat' respectively, so they are replaced with these shorter roots.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus