Learn how a Trie (Prefix Tree) solves the Replace Words problem in O(D + S) time with a line-by-line Go walkthrough and step-by-step execution visualizer.
The Problem
Given a dictionary of root words and a space-separated sentence, replace every word in the sentence with the shortest root in the dictionary that is a prefix of it. If a word has no matching root, leave it unchanged.
Standard Replacement
Dictionary: ["cat", "bat", "rat"]
Sentence: "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Nested Roots (Shortest Wins)
Dictionary: ["catt", "cat", "bat", "rat"]
Sentence: "the cattle was rattled by the battery"
Output: "the cat was rat by the bat" (both "cat" and "catt" match "cattle", so "cat" wins)
Why Use a Trie?
A Trie (pronounced "try", also called a prefix tree) stores strings character by character so words with the same prefix share the same path from the root.
| Feature | Trie (Prefix Tree) | Hash Map |
|---|---|---|
| Exact lookup | average | |
| Prefix matching | — walk down the tree | — must slice every prefix |
| Shortest-prefix match | Stop at the first isEnd == true | Must check prefixes from length 1 to |
Because lookup time depends only on the length of the word () and not the size of the dictionary (), a Trie is ideal for prefix replacement. With total dictionary characters and sentence length , the full algorithm runs in time.
Interactive Visualizer
Step through both phases of the Go algorithm below—Build Phase (inserting dictionary roots) and Replace Phase (scanning and replacing sentence words in place):
The Go Solution
package main
import "strings"
type rootNode struct {
children [26]*rootNode
isEnd bool
}
func replaceWords(dictionary []string, sentence string) string {
// 1. Build the Trie from the dictionary
root := &rootNode{}
for _, d := range dictionary {
curr := root
for i := 0; i < len(d); i++ {
c := d[i] - 'a'
if curr.children[c] == nil {
curr.children[c] = &rootNode{}
}
curr = curr.children[c]
}
curr.isEnd = true
}
// 2. Scan each word and replace with its shortest root
words := strings.Split(sentence, " ")
for idx, w := range words {
curr := root
for i := 0; i < len(w); i++ {
c := w[i] - 'a'
if curr.children[c] == nil {
break
}
curr = curr.children[c]
if curr.isEnd {
words[idx] = w[:i+1]
break
}
}
}
return strings.Join(words, " ")
}
instudia Editorial Team
Academic & Career Team
ISO Certified Skill Institute
Official articles and curriculum guides prepared by instudia faculty and industry mentors in Dimapur.
Relevant Courses at Instudia



