Problem overview
The method replaceWords receives an array of strings roots and a string sentence whose words are separated by single spaces. It returns the sentence after each word that starts with a root has been replaced by that root. If a word starts with several roots, the shortest wins. A root can also be the whole word, and a word that starts with no root stays unchanged.
With roots = ["sun", "snow"] and the sentence "sunny days and snowy nights", the result is "sun days and snow nights". With roots = ["book", "bookworm"] and "bookworms read books", the word bookworms starts with both roots, and the shorter one, book, is used: the result is "book read book". With roots = ["moon"], the word mo in "mo moonlight moon" is shorter than the root, so it stays: "mo moon moon".
Approach: put the roots in a trie
For one word, the brute-force way is to test every root with a prefix check and keep the shortest match. With up to 1,000 roots and up to 10,000 words, that repeats a lot of work. A trie answers the question for all roots at once.
A trie is a tree with one node per prefix. Roots that start the same way share a path from the top node. Each node has a dictionary from the next letter to the child node, and an isEnd flag that is true where some root ends. Walking down the trie along a word passes through every root the word starts with, in order of length, because a shorter root ends higher on the path.
So the walk for a word can stop at the first node where isEnd is true: that is the shortest root. The walk also stops when the word runs out of letters, or when the trie has no child for the next letter. In both cases no root fits, and the word is kept as it is.
The flag is needed because a root can be a prefix of a longer root. In the second example the node for book is in the middle of the path to bookworm. Only the flag says that a root ends there.
Step by step
- Add the children dictionary to
TrieNode:[Character: TrieNode], starting as[:]. Looping over aStringgives characters, so they are the keys. - Add
var isEnd = false, set totruewhere a root ends. - Create the top node,
trie, as alet. It always refers to the same node. The namerootis left for the loop variable that holds each root. - Loop over the roots to insert each one.
- Start a
var nodeattrie, because every root is inserted from the top. - Loop over the characters of the root. Each one goes one level down.
- Create the child if it is missing. A dictionary lookup for a missing key gives
nil. - Move
nodeto the child withnode.children[c]!. The lookup is an optional, and the!is safe because theifmade sure the child exists. - Mark the end with
node.isEnd = true, after the inner loop and inside the outer one. - Create
var result = [String]()to collect the new words. - Loop over
sentence.split(separator: " "). Each piece is aSubstring, a view into the sentence. - Convert the word to an array:
let letters = Array(word). A string cannot be read at an integer position in Swift, but an array of characters can. - Start a
var nodeattriefor this word. - Start
var length = 0. It counts the letters walked, which is also the length of the root once one is found. - Write the loop condition: no root ends at
node(!node.isEnd),length < letters.count, andnode.children[letters[length]] != nil. The conditions are joined with&&, which stops at the first false part, so the length is checked before the letter at that index is read. - Move down one level in the loop body and add 1 to
length. - If
node.isEndistrue, append the root, which is the firstlengthletters of the word:String(word.prefix(length)). - Otherwise append the whole word,
String(word). - Join the words with single spaces:
result.joined(separator: " ").
The solution in Swift
class TrieNode {
var children: [Character: TrieNode] = [:]
var isEnd = false
}
class Solution {
func replaceWords(_ roots: [String], _ sentence: String) -> String {
let trie = TrieNode()
for root in roots {
var node = trie
for c in root {
if node.children[c] == nil {
node.children[c] = TrieNode()
}
node = node.children[c]!
}
node.isEnd = true
}
var result = [String]()
for word in sentence.split(separator: " ") {
let letters = Array(word)
var node = trie
var length = 0
while !node.isEnd && length < letters.count && node.children[letters[length]] != nil {
node = node.children[letters[length]]!
length += 1
}
if node.isEnd {
result.append(String(word.prefix(length)))
} else {
result.append(String(word))
}
}
return result.joined(separator: " ")
}
}
Swift details worth knowing:
split(separator: " ")returns an array ofSubstringvalues. They share storage withsentence, so the solution wraps them inString(...)before adding them to an array ofString.TrieNodeis a class, sovar node = trieis another name for the same object. Changes made throughnodechange the trie.- When the walk ends because of the word,
node.isEndis checked, not the other conditions. If the loop ended at a node where a root ends, that node is the answer. If it ended for any other reason,node.isEndisfalse: the loop only continues while the flag isfalse, so it can't have moved past a node with the flag set.
Complexity
Let S be the total number of letters in the roots and in the sentence. Building the trie visits each root letter once. Each word's walk is at most as long as the word, so all the walks together cost at most the length of the sentence. The time is O(S). The trie and the result take O(S) extra space.
Edge cases and common mistakes
- A word shorter than a root. The walk runs out of letters before reaching a flagged node, so the word stays:
moagainstmoon. - The word equals a root. The walk reaches the flag on the last letter, and the root is the word itself.
- Several roots fit. Stopping at the first flag gives the shortest. Continuing to the deepest flag would give the longest, which is wrong here:
catalogwith rootscatandcatalogbecomescat. - A partial match. A word can follow part of a root's path without reaching its end. With the root
moon, the wordmoosesharesmoowith it but never reaches the flag, so it stays. Checking the flag at the end is what avoids cutting such a word. - Reading past the end of the word. Putting
length < letters.countafter the dictionary lookup would index outside the array and crash. Keep the order of the conditions. - Returning substrings. Appending a
Substringto a[String]does not compile; convert withString(...).
Testing
Results from the solution above:
| roots | sentence | Result |
|---|---|---|
["sun", "snow"] | "sunny days and snowy nights" | "sun days and snow nights" |
["book", "bookworm"] | "bookworms read books" | "book read book" |
["moon"] | "mo moonlight moon" | "mo moon moon" |
["a", "b"] | "cat bat rat" | "cat b rat" |
["cat", "catalog"] | "catalog cattle cat ca" | "cat cat cat ca" |
["x"] | "hello" | "hello" |
