Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Trie Autocomplete Implementation in Go

14 min readintermediate
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Trie Autocomplete runs in O(m) time and O(n*m) space, in Go as in every other language.
  • ✓No trie in the standard library and none planned. The node is a struct with children map[rune]*Node, or [26]*Node when the alphabet is fixed and you care about allocation.
  • ✓Range over the string, for _, r := range word, so you get runes; a reviewer will flag word[i] immediately because that is a byte.
  • ✓The Go trap: Go deliberately randomises map iteration order on every run of the same binary. A completion walk written as for r := range node.children returns the same set in a different order each time the process starts, so a table test passes on your laptop and flakes in CI, and users watching a typeahead see the list reshuffle between requests.
  • ✓A rune-keyed map hashes a 4-byte value and probes an 8-slot bucket per level, and every interior node contributes a map header plus at least one bucket as separate heap objects (leaves keep a nil map and cost nothing extra, which is why the lazy allocation above matters).

What Trie Autocomplete actually is

A trie stores a set of strings as a tree where each edge carries one character and every node is the shared prefix of everything beneath it. Walking m characters lands you on the subtree of all completions, so prefix lookup costs O(m) regardless of dictionary size; enumerating k suggestions then costs O(k) plus the length of what you emit. Engineers reach for it for search-box typeahead, command palettes, IP/route tables and spell correction: anywhere the query is a prefix and the answer set must be produced per keystroke. If the dictionary is static and read-only, a sorted array plus binary search is usually smaller and faster.

Trie Autocomplete in Go: what you actually reach for

No trie in the standard library and none planned. The node is a struct with children map[rune]*Node, or [26]*Node when the alphabet is fixed and you care about allocation. Descent uses the comma-ok form next, ok := cur.children[r]. sort.Slice and sort.Strings from the sort package order the output; strings.HasPrefix plus sort.SearchStrings over a sorted []string is the stdlib-only alternative that needs no trie at all. If you want a package, github.com/derekparker/trie is the commonly vendored one.

Go implementation

Range over the string, for _, r := range word, so you get runes; a reviewer will flag word[i] immediately because that is a byte. Return a nil slice for no matches rather than an allocated empty one, and preallocate the result with make([]string, 0, limit). The node type stays unexported with a New() constructor. Lazily allocate the children map on first insert so leaves do not each carry an empty map header.
go
package trie

import "sort"

type Node struct {
	children map[rune]*Node
	isWord   bool
}

func New() *Node { return &Node{} }

func (n *Node) Insert(word string) {
	cur := n
	for _, r := range word {
		if cur.children == nil {
			cur.children = make(map[rune]*Node, 4)
		}
		next, ok := cur.children[r]
		if !ok {
			next = New()
			cur.children[r] = next
		}
		cur = next
	}
	cur.isWord = true
}

func (n *Node) Complete(prefix string, limit int) []string {
	cur := n
	for _, r := range prefix {
		next, ok := cur.children[r]
		if !ok {
			return nil
		}
		cur = next
	}
	out := make([]string, 0, limit)
	var walk func(*Node, string)
	walk = func(node *Node, path string) {
		if len(out) >= limit {
			return
		}
		if node.isWord {
			out = append(out, path)
		}
		keys := make([]rune, 0, len(node.children))
		for r := range node.children {
			keys = append(keys, r)
		}
		sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })
		for _, r := range keys {
			walk(node.children[r], path+string(r))
		}
	}
	walk(cur, prefix)
	return out
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Go-specific trap

Go deliberately randomises map iteration order on every run of the same binary. A completion walk written as for r := range node.children returns the same set in a different order each time the process starts, so a table test passes on your laptop and flakes in CI, and users watching a typeahead see the list reshuffle between requests. There is no flag to turn it off: collect the keys into a slice and sort.Slice them, or key children by [26]*Node. Go is the loudest case but not the only one: Rust's std HashMap (RandomState) and Swift's Dictionary (per-process random hash seed since Swift 4.2) also reshuffle between runs, so the same guard is needed there. Python dicts, JavaScript Maps, Java's HashMap and .NET's Dictionary are the ones stable enough in practice for the bug to stay hidden.

Performance in Go, beyond the O(m)

A rune-keyed map hashes a 4-byte value and probes an 8-slot bucket per level, and every interior node contributes a map header plus at least one bucket as separate heap objects (leaves keep a nil map and cost nothing extra, which is why the lazy allocation above matters). Because those objects are pointer-dense, a large trie measurably lengthens GC mark phases even though nothing is being freed. [26]*Node arrays remove the hashing and the map allocation but cost 208 bytes per node on 64-bit and are wasteful for sparse alphabets. path + string(r) allocates a new string per branch; append into a reused []byte and convert once at emit. The asymptotic cost is the same in every language, O(m) time and O(n*m) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Trie Autocomplete between languages.

Real-World Applications

Trie Autocomplete applies wherever its problem shape appears in your own code. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Trie Autocomplete helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Trie Autocomplete appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Trie Autocomplete over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Trie Autocomplete to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Trie Autocomplete?

No trie in the standard library and none planned. The node is a struct with children map[rune]*Node, or [26]*Node when the alphabet is fixed and you care about allocation. Descent uses the comma-ok form next, ok := cur.children[r]. sort.Slice and sort.Strings from the sort package order the output; strings.HasPrefix plus sort.SearchStrings over a sorted []string is the stdlib-only alternative that needs no trie at all. If you want a package, github.com/derekparker/trie is the commonly vendored one.

What is the most common Go mistake when implementing Trie Autocomplete?

Go deliberately randomises map iteration order on every run of the same binary. A completion walk written as for r := range node.children returns the same set in a different order each time the process starts, so a table test passes on your laptop and flakes in CI, and users watching a typeahead see the list reshuffle between requests. There is no flag to turn it off: collect the keys into a slice and sort.Slice them, or key children by [26]*Node. Go is the loudest case but not the only one: Rust's std HashMap (RandomState) and Swift's Dictionary (per-process random hash seed since Swift 4.2) also reshuffle between runs, so the same guard is needed there. Python dicts, JavaScript Maps, Java's HashMap and .NET's Dictionary are the ones stable enough in practice for the bug to stay hidden.

How does Trie Autocomplete actually perform in Go?

A rune-keyed map hashes a 4-byte value and probes an 8-slot bucket per level, and every interior node contributes a map header plus at least one bucket as separate heap objects (leaves keep a nil map and cost nothing extra, which is why the lazy allocation above matters). Because those objects are pointer-dense, a large trie measurably lengthens GC mark phases even though nothing is being freed. [26]*Node arrays remove the hashing and the map allocation but cost 208 bytes per node on 64-bit and are wasteful for sparse alphabets. path + string(r) allocates a new string per branch; append into a reused []byte and convert once at emit. Time complexity is O(m) and space is O(n*m).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

If you are a student, see what Devin offers students for free on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.