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

Suffix Array Implementation in Go

19 min readadvanced
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

  • ✓Suffix Array runs in O(n log n) time and O(n) space, in Go as in every other language.
  • ✓Go is the only language in this set with a suffix array in its standard library: index/suffixarray.
  • ✓Reviewers reach for index/suffixarray first and want a comment justifying any hand-rolled build.
  • ✓The Go trap: suffixarray.New keeps your slice; it does not copy the text. Bytes() returns that same backing array and the documentation says it must not be modified, so a caller who reuses the buffer - a pooled read buffer, or an append that happened to fit inside cap - silently invalidates every later Lookup with no error, no panic and no way to notice.
  • ✓sort.Slice pays a reflectlite.Swapper indirect call on every swap; slices.SortFunc is instantiated for int32 so the swaps are direct int32 moves, which is a real win across n log n rounds.

What Suffix Array actually is

A suffix array is the sorted list of the starting positions of every suffix of a text: n integers, instead of the pointers-plus-nodes a suffix tree needs for the same queries. Binary-searching it finds every occurrence of a pattern in O(m log n), and paired with an LCP array (Kasai, O(n)) it answers longest-repeated-substring, distinct-substring counts and the Burrows-Wheeler transform. You reach for it when one text is searched many times and the index has to stay small: log parsing, genomics, full-text search over a fixed corpus.

Suffix Array in Go: what you actually reach for

Go is the only language in this set with a suffix array in its standard library: index/suffixarray. suffixarray.New(data []byte) *Index builds it, idx.Lookup(pat []byte, n int) []int returns occurrences (n < 0 means all), idx.FindAllIndex(re *regexp.Regexp, n int) does regexp search over the index, and Read/Write serialise it. The Index deliberately does not export the permutation - Bytes() hands back the indexed data, not the array - so when you need the array itself for LCP, BWT or distinct-substring counting you hand-roll doubling over []int32 with slices.SortFunc.

Go implementation

Reviewers reach for index/suffixarray first and want a comment justifying any hand-rolled build. When you do roll one they insist on slices.SortFunc - generic, instantiated per element type, cmp returns an int - over sort.Slice, which routes every swap through a reflect-based swapper. They want []int32 rather than []int, make() with the exact length rather than append growth, and the comparison hoisted onto a struct method so its captured slice stops escaping each round.
go
package sa

import (
	"index/suffixarray"
	"slices"
)

// Stdlib route. New RETAINS data -- never mutate it afterwards.
func Occurrences(data, pat []byte) []int {
	idx := suffixarray.New(data)
	hits := idx.Lookup(pat, -1) // -1 = all matches; the result is UNSORTED
	slices.Sort(hits)
	return hits
}

// builder holds the round state on a type, so no closure captures the rank
// slice and forces it to escape once per round.
type builder struct {
	rank []int32
	k, n int
}

func (b *builder) key(i int32) (int32, int32) {
	if j := int(i) + b.k; j < b.n {
		return b.rank[i], b.rank[j]
	}
	return b.rank[i], 0
}

func (b *builder) cmp(x, y int32) int {
	x1, x2 := b.key(x)
	y1, y2 := b.key(y)
	if x1 != y1 {
		return int(x1) - int(y1)
	}
	return int(x2) - int(y2)
}

// Hand-rolled doubling, for when you need the array itself.
func Build(text []byte) []int32 {
	n := len(text)
	sa, rank, tmp := make([]int32, n), make([]int32, n), make([]int32, n)
	for i := range sa {
		sa[i], rank[i] = int32(i), int32(text[i])+1
	}
	b := &builder{rank: rank, n: n}
	for k := 1; k < n; k <<= 1 {
		b.k, b.rank = k, rank // one allocation, reused every round
		slices.SortFunc(sa, b.cmp)
		tmp[sa[0]] = 1
		for w := 1; w < n; w++ {
			p1, p2 := b.key(sa[w-1])
			c1, c2 := b.key(sa[w])
			tmp[sa[w]] = tmp[sa[w-1]]
			if p1 != c1 || p2 != c2 {
				tmp[sa[w]]++
			}
		}
		rank, tmp = tmp, rank
		if int(rank[sa[n-1]]) == n {
			break
		}
	}
	return sa
}

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

suffixarray.New keeps your slice; it does not copy the text. Bytes() returns that same backing array and the documentation says it must not be modified, so a caller who reuses the buffer - a pooled read buffer, or an append that happened to fit inside cap - silently invalidates every later Lookup with no error, no panic and no way to notice. The second Go-shaped trap sits in the same package: Lookup is documented to return an UNSORTED list of at most n indices. Code that assumes ascending positions is correct on a small corpus and reorders on a big one. Sort the result yourself with slices.Sort if order matters.

Performance in Go, beyond the O(n log n)

sort.Slice pays a reflectlite.Swapper indirect call on every swap; slices.SortFunc is instantiated for int32 so the swaps are direct int32 moves, which is a real win across n log n rounds. The comparison itself is still an indirect call through the func value - SortFunc is far over the inlining budget - so keep its body tiny. A comparison closure that captures the rank slice forces that slice header to escape to the heap, adding a pointer hop per comparison - hoisting the ranks into a struct with a method removes it. []int32 halves the resident set against []int on 64-bit and, holding no pointers, is skipped outright by the garbage collector's scan. The asymptotic cost is the same in every language, O(n log 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 Suffix Array between languages.

Real-World Applications

Suffix Array is used extensively in production software: database engines, compilers, operating systems, and application frameworks all use Suffix Array internally. In Go specifically, the standard library and popular packages like gin and gorm apply these principles. Understanding Suffix Array helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Suffix Array appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Suffix Array 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 Suffix Array 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 Suffix Array?

Go is the only language in this set with a suffix array in its standard library: index/suffixarray. suffixarray.New(data []byte) *Index builds it, idx.Lookup(pat []byte, n int) []int returns occurrences (n < 0 means all), idx.FindAllIndex(re *regexp.Regexp, n int) does regexp search over the index, and Read/Write serialise it. The Index deliberately does not export the permutation - Bytes() hands back the indexed data, not the array - so when you need the array itself for LCP, BWT or distinct-substring counting you hand-roll doubling over []int32 with slices.SortFunc.

What is the most common Go mistake when implementing Suffix Array?

suffixarray.New keeps your slice; it does not copy the text. Bytes() returns that same backing array and the documentation says it must not be modified, so a caller who reuses the buffer - a pooled read buffer, or an append that happened to fit inside cap - silently invalidates every later Lookup with no error, no panic and no way to notice. The second Go-shaped trap sits in the same package: Lookup is documented to return an UNSORTED list of at most n indices. Code that assumes ascending positions is correct on a small corpus and reorders on a big one. Sort the result yourself with slices.Sort if order matters.

How does Suffix Array actually perform in Go?

sort.Slice pays a reflectlite.Swapper indirect call on every swap; slices.SortFunc is instantiated for int32 so the swaps are direct int32 moves, which is a real win across n log n rounds. The comparison itself is still an indirect call through the func value - SortFunc is far over the inlining budget - so keep its body tiny. A comparison closure that captures the rank slice forces that slice header to escape to the heap, adding a pointer hop per comparison - hoisting the ranks into a struct with a method removes it. []int32 halves the resident set against []int on 64-bit and, holding no pointers, is skipped outright by the garbage collector's scan. Time complexity is O(n log 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

Before paying full price for a tool, check the student deals on AI and developer tools listed 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.