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

Longest Common Substring 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

  • ✓Longest Common Substring runs in O(n*m) time and O(n*m) space, in Go as in every other language.
  • ✓The strings package has Index, Contains and Builder but no LCSubstring. Go is the outlier here in one respect: it ships a real substring index in index/suffixarray - suffixarray.New([]byte) plus (*Index).Lookup([]byte, n) - which none of the other seven standard libraries provide, and which turns the binary-search-on-length variant into a practical alternative to the DP.
  • ✓Return byte offsets (start, end int) and let the caller slice - a Go slice of a string shares storage, so this is the zero-allocation shape a reviewer expects.
  • ✓The Go trap: a[i] on a string is a byte and it compiles happily - Rust refuses, Go does not - so the natural DP silently reports a common run that is not valid UTF-8.
  • ✓No JIT means no warmup and no profile-driven bounds-check elimination beyond what the compiler proves statically, so shape matters: slice each row once into a local and index with a variable the compiler can bound against len(row).

What Longest Common Substring actually is

The longest run of CONSECUTIVE elements that appears in both sequences - not to be confused with longest common subsequence, which may skip elements. The textbook solution is a table where dp[i][j] holds the length of the match ending exactly at a[i-1] and b[j-1]: equal elements extend the diagonal, unequal elements reset to zero, and you track the running maximum. Engineers reach for it in diff tools looking for anchor blocks, plagiarism and duplicate-content checks, read overlap in bioinformatics, log deduplication, and fuzzy matching of product titles. Suffix automata or suffix arrays get you to O(n+m) when the inputs are large enough to care.

Longest Common Substring in Go: what you actually reach for

The strings package has Index, Contains and Builder but no LCSubstring. Go is the outlier here in one respect: it ships a real substring index in index/suffixarray - suffixarray.New([]byte) plus (*Index).Lookup([]byte, n) - which none of the other seven standard libraries provide, and which turns the binary-search-on-length variant into a practical alternative to the DP. For correct UTF-8 handling of the result, unicode/utf8 gives RuneStart(byte) bool and DecodeLastRuneInString.

Go implementation

Return byte offsets (start, end int) and let the caller slice - a Go slice of a string shares storage, so this is the zero-allocation shape a reviewer expects. Returning a[start:end] is equally allocation-free, but it pins the entire parent backing array for as long as the result lives - returning offsets (or strings.Clone on the result) is what lets a 50 MB input be collected. Two flat []int32 rows swapped by assignment, never [][]int built in a loop. Accept string, not []byte, unless you mutate. Package lcs with func Longest avoids the lcs.LCSLongest stutter. Table-driven tests with subtests, and a testing.B benchmark in the same PR if you claim it is fast.
go
package lcs

import "unicode/utf8"

// Longest returns the byte offsets [start, end) in a of a longest common substring.
func Longest(a, b string) (int, int) {
	prev := make([]int32, len(b)+1)
	cur := make([]int32, len(b)+1)
	best, end := 0, 0

	for i := 1; i <= len(a); i++ {
		ca := a[i-1] // a byte, not a rune
		for j := 1; j <= len(b); j++ {
			if ca == b[j-1] {
				cur[j] = prev[j-1] + 1
				if int(cur[j]) > best {
					best, end = int(cur[j]), i
				}
			} else {
				cur[j] = 0
			}
		}
		prev, cur = cur, prev
	}

	start := end - best
	for start < end && !utf8.RuneStart(a[start]) {
		start++
	}
	for end > start {
		r, size := utf8.DecodeLastRuneInString(a[start:end])
		if r == utf8.RuneError && size <= 1 {
			end--
			continue
		}
		break
	}
	return start, end
}

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

a[i] on a string is a byte and it compiles happily - Rust refuses, Go does not - so the natural DP silently reports a common run that is not valid UTF-8. Printed with %s it renders as U+FFFD, len() of the result disagrees with the count you get from range over it, and ranging over that result yields utf8.RuneError for every broken sequence, so a for _, r := range result { if r == 'e' } scan never matches - while the tempting result == 'e' does not even compile, since a string and a rune are mismatched types. Trim both ends with utf8.RuneStart and DecodeLastRuneInString. Converting to []rune fixes correctness but copies the whole string and renumbers every index, so the offsets you return no longer address the original bytes.

Performance in Go, beyond the O(n*m)

No JIT means no warmup and no profile-driven bounds-check elimination beyond what the compiler proves statically, so shape matters: slice each row once into a local and index with a variable the compiler can bound against len(row). Two []int32 rows are pointer-free, so they land in noscan spans and the GC never touches the 400 KB of counters - but the inner rows of a [][]int are pointer-free as well, so the flat layout's win is locality and allocation count, not GC scanning: one contiguous row keeps the whole sweep in cache, while n separately allocated rows scatter across size classes and add n objects for the GC to mark. Rows escape to the heap; reuse them across calls with a sync.Pool when this sits in a request path. The asymptotic cost is the same in every language, O(n*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 Longest Common Substring between languages.

Real-World Applications

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

Interview Tips & Practice

Longest Common Substring 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 Longest Common Substring 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 Longest Common Substring 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 Longest Common Substring?

The strings package has Index, Contains and Builder but no LCSubstring. Go is the outlier here in one respect: it ships a real substring index in index/suffixarray - suffixarray.New([]byte) plus (*Index).Lookup([]byte, n) - which none of the other seven standard libraries provide, and which turns the binary-search-on-length variant into a practical alternative to the DP. For correct UTF-8 handling of the result, unicode/utf8 gives RuneStart(byte) bool and DecodeLastRuneInString.

What is the most common Go mistake when implementing Longest Common Substring?

a[i] on a string is a byte and it compiles happily - Rust refuses, Go does not - so the natural DP silently reports a common run that is not valid UTF-8. Printed with %s it renders as U+FFFD, len() of the result disagrees with the count you get from range over it, and ranging over that result yields utf8.RuneError for every broken sequence, so a for _, r := range result { if r == 'e' } scan never matches - while the tempting result == 'e' does not even compile, since a string and a rune are mismatched types. Trim both ends with utf8.RuneStart and DecodeLastRuneInString. Converting to []rune fixes correctness but copies the whole string and renumbers every index, so the offsets you return no longer address the original bytes.

How does Longest Common Substring actually perform in Go?

No JIT means no warmup and no profile-driven bounds-check elimination beyond what the compiler proves statically, so shape matters: slice each row once into a local and index with a variable the compiler can bound against len(row). Two []int32 rows are pointer-free, so they land in noscan spans and the GC never touches the 400 KB of counters - but the inner rows of a [][]int are pointer-free as well, so the flat layout's win is locality and allocation count, not GC scanning: one contiguous row keeps the whole sweep in cache, while n separately allocated rows scatter across size classes and add n objects for the GC to mark. Rows escape to the heap; reuse them across calls with a sync.Pool when this sits in a request path. Time complexity is O(n*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

Still choosing? See the top-rated tools by category 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.