Replace Words solution explained
Replace Words gives you a list of roots and a sentence, and asks you to replace every word that starts with a root by the shortest such root, leaving other words alone. Put the roots in a trie and walk each word through it letter by letter; the first node that ends a root is the shortest match, and a missing child means there is none. That is O(total letters examined) after building the trie, with a set of roots as a simpler alternative.
By Evin JohnPublished 7 min read
The problem, in plain terms
You have a dictionary of roots, short strings like un or re, and a sentence of lowercase words separated by single spaces. A root can be followed by more letters to form a longer word. For each word in the sentence, if one or more roots are prefixes of it, replace the word with the shortest of those roots. Words with no matching root stay as they are. Return the new sentence.
roots: re, read, play, pl, un
sentence: the reader replayed the unplugged plan
reader -> re (re and read both match; re is shorter)
replayed -> re
unplugged -> un
plan -> pl
the -> the (no root)
result: the re re the un plClarify the input format before coding: single spaces only, lowercase only, and whether a root can be empty or repeated. An empty root would technically be a prefix of every word, so treat it as invalid unless told otherwise; the code below ignores it.
What the interviewer is checking
This is a gentle trie question. The interviewer wants to see you notice that many roots share beginnings and that the shortest match is found by walking down, not by sorting roots. It is also a check on string handling basics: splitting, rebuilding the sentence, and not mutating something you are iterating over. A clean set-based answer followed by the trie as an improvement is a good arc for a 30-minute slot.
Brute force
For every word, test every root with a starts-with check and keep the shortest root that passes. With N roots of length up to R and a sentence of K words, that is O(K × N × R). It is correct and easy to verify, which is why it served as the reference for the tests here, but every word re-reads the same root letters from scratch.
A simpler improvement: a set of roots
Put the roots in a hash set and collect the distinct root lengths in increasing order. For each word, try its prefix of each length, shortest first, and stop at the first prefix that is in the set. Since lengths go up, the first hit is the shortest root. This avoids scanning the root list per word, and it is often enough to pass.
def replace_words(roots, sentence):
root_set = {r for r in roots if r} # an empty root would match everything
lengths = sorted({len(r) for r in root_set}) # try short roots first
out = []
for word in sentence.split(" "):
for size in lengths:
if size > len(word):
break
if word[:size] in root_set:
word = word[:size]
break
out.append(word)
return " ".join(out)Each attempt slices a prefix and hashes it, which costs time proportional to its length, so a word can cost up to the sum of the root lengths tried. That is fine when roots are short, and it is the reason the trie is the stronger answer when they are long.
The optimal approach: a trie of roots
Pattern: prefix lookup with a trie. Insert every root and mark the node where it ends. For each word, start at the top of the trie and follow one letter at a time. If the next letter has no child, no root is a prefix of the word, so keep the word. If you land on a node marked as a root end, you have found the shortest root, because any longer root would end deeper on the same path. Each letter is looked at once, and the walk never goes past the longest root.
function replaceWords(roots, sentence) {
const trie = {};
for (const r of roots) {
let node = trie;
for (const ch of r) node = node[ch] ??= {};
node.isRoot = true;
}
return sentence
.split(" ")
.map((word) => {
let node = trie;
for (let i = 0; i < word.length; i++) {
node = node[word[i]];
if (!node) break; // no root starts this way
if (node.isRoot) return word.slice(0, i + 1); // first root found is the shortest
}
return word;
})
.join(" ");
}The trie uses plain objects with single letters as keys and an isRoot flag. That is safe here because letter keys are one character long and can never collide with the flag or with built-in property names. If the alphabet were arbitrary, a Map per node, or an object created with Object.create(null), would remove any doubt.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Every root against every word | O(K × N × R) | O(1) beyond the output |
| Set of roots, shortest length first | O(total root letters) to build, then up to O(min(L, R)²) per word | O(total root letters) |
| Trie of roots | O(total root letters) to build, then O(min(L, R)) per word | O(total root letters) nodes |
Building the output string is O(length of the sentence) in every version. In languages where strings are immutable, collect the pieces in a list and join once, as both snippets do, instead of adding to a string in a loop.
Edge cases to test
- An empty root list: the sentence comes back unchanged.
- A root equal to a whole word, which replaces the word with itself.
- Two roots where one is a prefix of the other, like re and read, to confirm the shorter one wins.
- A root longer than the word, which must not match.
- A sentence with one word, and a word that shares a beginning with a root but then diverges.
Common mistakes
- Walking the whole word through the trie and returning the deepest root end, which gives the longest root instead of the shortest.
- Forgetting to stop when a letter has no child, which then reads a property of undefined or keeps a wrong node.
- Sorting roots by length and checking each with starts-with for every word, which is still the brute force in disguise.
- Letting an empty root into the set, so every word turns into an empty string.
- Splitting on any whitespace and then joining with single spaces when the input format was not confirmed.
How to explain it out loud
Fictional example
- Candidate
- The direct way is to test every root against every word with starts-with, but that rereads the same prefixes over and over.
- Candidate
- I'll put the roots in a trie. For each word I walk down letter by letter. The first node I reach that ends a root is the shortest root, since any other matching root would end further down this same path.
- Candidate
- If a letter has no child I stop and keep the word. So each word costs at most the length of the longest root, and I join the results with spaces at the end.
Related problems
If tries are new to you, start with Implement Trie. Matching words at the end of an incoming stream, with the trie built from reversed words, is Stream of Characters. Deciding whether a word is made entirely of other dictionary words is Concatenated Words.
Natively while you prepare
Easy trie questions are where interviewers expect a crisp explanation, so the talk matters as much as the code. During practice on a Mac or a Windows PC, Natively can read the problem from a screenshot and write an approach and code to compare with your own version. Its transcript of the practice session shows whether you justified why the first root end is the shortest. See how AI helps in coding interviews.
Questions people ask
How do you solve Replace Words?
Insert the roots into a trie. For each word, walk down the trie letter by letter; the first node that ends a root gives the shortest root, and a missing child means no root matches, so the word stays.
Why does the first root found in the trie give the shortest root?
All roots that are prefixes of a word lie on the same path from the top of the trie. Walking down, you meet them in order of length, so the first one reached is the shortest.
What is the time complexity of Replace Words?
Building the trie is linear in the total length of the roots. Each word then costs at most the length of the longest root, or its own length if shorter, plus linear time to build the output sentence.
Can you solve Replace Words without a trie?
Yes. Store the roots in a hash set, sort the distinct root lengths, and test each word's prefixes from the shortest length up. It is simpler, but slicing and hashing make each word cost more when roots are long.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
