Longest Common Substring 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
- ✓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
Longest Common Substring in Go: what you actually reach for
Go implementation
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 FreeThe Go-specific trap
Performance in Go, beyond the O(n*m)
Real-World Applications
Interview Tips & Practice
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).
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 trialStill choosing? See the top-rated tools by category 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.