Hornbill Festival!Explore Tech in Nagaland →
Enroll
BACK TO ALL BLOGS
ENGINEERING
DSA in Go · PART 1MediumTrie / Prefix Tree

Solving Replace Words in Go Usinga Trie (With Interactive Visualizer)

instudia Editorial Team

instudia Editorial Team

Academic & Career Team

ISO Certified Skill Institute

Published

4 December 2026

Read Time

6 min read

Solving Replace Words in Go Using a Trie (With Interactive Visualizer)

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.

01

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)

02

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.

FeatureTrie (Prefix Tree)Hash Map
Exact lookupO(L)O(L)O(L)O(L) average
Prefix matchingO(L)O(L) — walk down the treeO(N⋅L)O(N \cdot L) — must slice every prefix
Shortest-prefix matchStop at the first isEnd == trueMust check prefixes from length 1 to LL

Because lookup time depends only on the length of the word (LL) and not the size of the dictionary (NN), a Trie is ideal for prefix replacement. With total dictionary characters DD and sentence length SS, the full algorithm runs in O(D+S)O(D + S) time.

03

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):

04

The Go Solution

go
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
About the Author

instudia Editorial Team

Academic & Career Team

ISO Certified Skill Institute

Official articles and curriculum guides prepared by instudia faculty and industry mentors in Dimapur.

Verified Profiles:Website ↗
Right time to

Turn Learning into
A Career.