648. Replace Words
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to replace words in a sentence with their shortest possible "root" from a given dictionary. If a word in the sentence starts with a root from the dictionary (making it a "derivative"), we must perform this replacement. If a word could be formed from multiple roots, the one with the shortest length should be used.
Solution
Replace Words in Python
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
# Using a dictionary as a Trie node.
# A special key '#' can store the word if it's a root.
trie = {}
# 1. Build the Trie from the dictionary.
for word in dictionary:
node = trie
for char in word:
if char not in node:
node[char] = {}
node = node[char]
node['#'] = word
words = sentence.split(' ')
result_words = []
# 2. Iterate through words in the sentence.
for word in words:
node = trie
replacement = word # Default to the original word.
# 3. Search for the shortest root prefix.
for char in word:
if char not in node:
# No prefix continuation, so no root is possible.
break
node = node[char]
if '#' in node:
# Found the shortest root because we traverse char by char.
replacement = node['#']
break
result_words.append(replacement)
return ' '.join(result_words)
Replace Words in Java
class Solution {
// Inner class for TrieNode
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word = null; // Store the word if this node is an end of a root
}
public String replaceWords(List<String> dictionary, String sentence) {
TrieNode root = new TrieNode();
// 1. Build the Trie from the dictionary.
for (String word : dictionary) {
TrieNode curr = root;
for (char c : word.toCharArray()) {
if (curr.children[c - 'a'] == null) {
curr.children[c - 'a'] = new TrieNode();
}
curr = curr.children[c - 'a'];
}
curr.word = word; // Mark the end of a root word.
}
// 2. Split sentence into words and replace them.
StringBuilder result = new StringBuilder();
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
String word = words[i];
String replacement = word; // Default to the original word.
TrieNode curr = root;
// 3. Search for the shortest root in the Trie.
for (char c : word.toCharArray()) {
if (curr.children[c - 'a'] == null) {
// No prefix continuation, so no root is possible.
break;
}
curr = curr.children[c - 'a'];
if (curr.word != null) {
// Found the shortest root because we traverse char by char.
replacement = curr.word;
break;
}
}
if (i > 0) {
result.append(" ");
}
result.append(replacement);
}
return result.toString();
}
}
Replace Words in C++
class Solution {
private:
// TrieNode structure for the prefix tree.
struct TrieNode {
TrieNode* children[26] = {nullptr};
std::string word = "";
};
public:
string replaceWords(vector<string>& dictionary, string sentence) {
// A custom deleter for the raw pointer Trie.
auto trie_deleter = [](TrieNode* root) {
if (!root) return;
std::vector<TrieNode*> q;
q.push_back(root);
while (!q.empty()) {
TrieNode* node = q.back();
q.pop_back();
for (int i = 0; i < 26; ++i) {
if (node->children[i]) {
q.push_back(node->children[i]);
}
}
delete node;
}
};
std::unique_ptr<TrieNode, decltype(trie_deleter)> root(new TrieNode(), trie_deleter);
// 1. Build the Trie from the dictionary.
for (const string& w : dictionary) {
TrieNode* curr = root.get();
for (char c : w) {
if (!curr->children[c - 'a']) {
curr->children[c - 'a'] = new TrieNode();
}
curr = curr->children[c - 'a'];
}
curr->word = w;
}
// 2. Split sentence into words and replace them.
stringstream ss(sentence);
string word;
string result = "";
bool first_word = true;
while (ss >> word) {
if (!first_word) {
result += " ";
}
TrieNode* curr = root.get();
string replacement = word; // Default to the original word.
// 3. Search for the shortest root in the Trie.
for (char c : word) {
if (!curr->children[c - 'a']) {
// No prefix continuation, so no root is possible.
break;
}
curr = curr->children[c - 'a'];
if (!curr->word.empty()) {
// Found the shortest root because we traverse char by char.
replacement = curr->word;
break;
}
}
result += replacement;
first_word = false;
}
return result;
}
};
Replace Words in TypeScript
function replaceWords(dictionary: string[], sentence: string): string {
// TrieNode class defined inside the function scope.
class TrieNode {
children: { [key: string]: TrieNode } = {};
word: string | null = null;
}
const root = new TrieNode();
// 1. Build the Trie from the dictionary.
for (const word of dictionary) {
let curr = root;
for (const char of word) {
if (!curr.children[char]) {
curr.children[char] = new TrieNode();
}
curr = curr.children[char];
}
curr.word = word;
}
const words = sentence.split(' ');
const resultWords: string[] = [];
// 2. Iterate through words in the sentence.
for (const word of words) {
let curr = root;
let replacement = word; // Default to the original word.
// 3. Search for the shortest root prefix.
for (const char of word) {
if (!curr.children[char]) {
// No prefix continuation, so no root is possible.
break;
}
curr = curr.children[char];
if (curr.word !== null) {
// Found the shortest root because we traverse char by char.
replacement = curr.word;
break;
}
}
resultWords.push(replacement);
}
return resultWords.join(' ');
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.