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

Run-Length Encoding Implementation in Go

11 min readbeginner
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

  • ✓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 replaces each maximal run of identical adjacent symbols with the symbol plus its repeat count: aaabbc becomes a3b2c. One left-to-right pass with a single symbol of lookahead, no dictionary, no sliding window, no back-references. Engineers reach for it where the data is already run-heavy: 1-bit fax and bitmap scanlines, PCX/BMP/TGA sprite masks, sparse column masks, and as the cheap final stage after a transform that manufactures runs, such as move-to-front output after Burrows-Wheeler. On random text it inflates, so the format almost always needs an escape or a literal-block mode.

Run-Length Encoding in Go: what you actually reach for

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.

Go implementation

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 Builder is passed as *strings.Builder, never by value. They will flag string(n) where n is an int count: that is a rune conversion, not a number, and go vet's stringintconv check fails the build in most CI setups; write strconv.Itoa(n). Exported functions carry a doc comment that starts with the function name, and the error-free path returns a plain string.
go
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 Free

The Go-specific 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'. 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).

Performance in Go, beyond the O(n)

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. The asymptotic cost is the same in every language, O(n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Run-Length Encoding between languages.

Real-World Applications

Run-Length Encoding 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 Run-Length Encoding helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Run-Length Encoding appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Run-Length Encoding 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 Run-Length Encoding 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 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).

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 Replit 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.