Run-Length Encoding Implementation in Go
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
- ✓Run-Length Encoding runs in O(n) time and O(n) space, in Go as in every other language.
- ✓strings.Builder is the accumulator: WriteRune for the symbol, WriteString(strconv.Itoa(n)) for the count, Grow(len(s)) up front, String() at the end.
- ✓Reviewers want strings.Builder with a Grow call, never out += part in a loop and never bytes.Buffer when the result is a string.
- ✓The Go trap: strings.Builder stores a pointer to itself and re-checks it on every write, so copying a Builder that has already been written to panics at runtime: 'strings: illegal use of non-zero Builder copied by value'.
- ✓strings.Builder.String() reinterprets the accumulated []byte as a string with no copy, whereas bytes.Buffer.String() copies the whole buffer, costing one extra full-length allocation per call.
What Run-Length Encoding actually is
Run-Length Encoding in Go: what you actually reach for
Go implementation
package rle
import (
"strconv"
"strings"
)
// Encode returns the run-length encoding of s, counting runes.
func Encode(s string) string {
var b strings.Builder
b.Grow(len(s))
var cur rune
n := 0
for _, r := range s { // range decodes UTF-8; the index is a byte offset
if n > 0 && r == cur {
n++
continue
}
flush(&b, cur, n) // pointer: copying a used Builder panics
cur, n = r, 1
}
flush(&b, cur, n)
return b.String()
}
func flush(b *strings.Builder, r rune, n int) {
if n == 0 {
return
}
b.WriteRune(r)
if n > 1 {
b.WriteString(strconv.Itoa(n)) // not string(n): that is a rune
}
}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 FreeThe Go-specific trap
Performance in Go, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Run-Length Encoding?
strings.Builder is the accumulator: WriteRune for the symbol, WriteString(strconv.Itoa(n)) for the count, Grow(len(s)) up front, String() at the end. Ranging over a string decodes UTF-8 for you and hands back rune values, so unicode/utf8 is rarely needed directly, though utf8.DecodeRuneInString is there when you must drive the cursor yourself. For byte output use bytes.Buffer, or strconv.AppendInt(dst, int64(n), 10) straight into your own []byte. The standard library has no adjacency group-by; slices offers no run-splitting helper either.
What is the most common Go mistake when implementing Run-Length Encoding?
strings.Builder stores a pointer to itself and re-checks it on every write, so copying a Builder that has already been written to panics at runtime: 'strings: illegal use of non-zero Builder copied by value'. The way it happens in an RLE is completely natural: you factor the emit step out as func flush(b strings.Builder, r rune, n int) and pass b instead of &b. go vet's copylocks check does not see it, because Builder guards itself with a self-pointer rather than an embedded noCopy lock. The empty-string test passes, because flush returns on n == 0 before it ever writes, so copyCheck never runs on the copy; the Builder itself is already non-zero by then, since Grow calls copyCheck and stamps b.addr = &b even for Grow(0).
How does Run-Length Encoding actually perform in Go?
strings.Builder.String() reinterprets the accumulated []byte as a string with no copy, whereas bytes.Buffer.String() copies the whole buffer, costing one extra full-length allocation per call. Grow(len(s)) matters because append doubling reallocates and copies logarithmically many times. strconv.Itoa returns a slice of a package-level constant string for values 0-99, so short run counts are allocation-free, and allocates from 100 up; strconv.AppendInt into your own buffer is free at any size. Ranging a string pays a UTF-8 decode per rune that s[i] does not. Time complexity is O(n) and space is O(n).
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 trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
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.