Levenshtein Distance 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
- ✓Levenshtein Distance runs in O(n*m) time and O(n*m) space, in Go as in every other language.
- ✓Nothing in the standard library, and golang.org/x/text does not carry one either. The community default is github.com/agnivade/levenshtein with levenshtein.ComputeDistance(a, b string) int, which converts to []rune and keeps two rows; github.com/texttheater/golang-levenshtein is the one to use when you need the edit script and not just the number.
- ✓Go reviewers want the allocations named and hoisted: two make([]int, n+1) calls before the loops, rows exchanged with prev, cur = cur, prev, and no append in the hot path.
- ✓The Go trap: for i, r := range s puts the BYTE offset in i, not the character position, so a loop that uses i as a DP row index jumps two to four slots per multi-byte rune and walks off the row on the first non-ASCII input.
- ✓[]rune(s) is a real heap allocation plus a full UTF-8 decode at 4 bytes per rune, and it escapes because it outlives the loop; for ASCII-heavy input []byte(s) is one quarter of that allocation and skips decoding entirely.
What Levenshtein Distance actually is
Levenshtein Distance in Go: what you actually reach for
Go implementation
package strdist
// Levenshtein reports the edit distance in runes, not bytes.
func Levenshtein(a, b string) int {
// convert ONCE: range over a string yields byte offsets, not positions
x, y := []rune(a), []rune(b)
if len(x) < len(y) {
x, y = y, x
}
if len(y) == 0 {
return len(x)
}
prev := make([]int, len(y)+1)
cur := make([]int, len(y)+1)
for j := range prev {
prev[j] = j
}
for i := 1; i <= len(x); i++ {
cur[0] = i
xi := x[i-1]
for j := 1; j <= len(y); j++ {
cost := 1
if xi == y[j-1] {
cost = 0
}
cur[j] = minInt(prev[j]+1, minInt(cur[j-1]+1, prev[j-1]+cost))
}
prev, cur = cur, prev
}
return prev[len(y)]
}
func minInt(a, b int) int {
if a < b {
return a
}
return b
}
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 Levenshtein Distance?
Nothing in the standard library, and golang.org/x/text does not carry one either. The community default is github.com/agnivade/levenshtein with levenshtein.ComputeDistance(a, b string) int, which converts to []rune and keeps two rows; github.com/texttheater/golang-levenshtein is the one to use when you need the edit script and not just the number. From std you get []rune(s) for indexable characters, utf8.RuneCountInString in unicode/utf8 for the length without allocating, and golang.org/x/text/unicode/norm for NFC folding.
What is the most common Go mistake when implementing Levenshtein Distance?
for i, r := range s puts the BYTE offset in i, not the character position, so a loop that uses i as a DP row index jumps two to four slots per multi-byte rune and walks off the row on the first non-ASCII input. Indexing compounds it: s[i] is a byte, not a rune, so an accented letter compares as two unrelated bytes and reports distance 2 where a human sees one substitution. Convert once with r := []rune(s) and index that slice. On ASCII test data both bugs are invisible, which is exactly how they reach production.
How does Levenshtein Distance actually perform in Go?
[]rune(s) is a real heap allocation plus a full UTF-8 decode at 4 bytes per rune, and it escapes because it outlives the loop; for ASCII-heavy input []byte(s) is one quarter of that allocation and skips decoding entirely. Slice reads are bounds-checked and the compiler only eliminates the check when the bound is derived from the slice itself, which the init loop's for j := range prev gets for free; the inner loop has to keep its counter form for the j-1 reads, so bound it on the row it writes, for j := 1; j < len(cur); j++, rather than on a separate len(y). In a hot service, allocate the two rows once per worker and reuse them across calls; the GC cost of two slices per comparison dominates at small string sizes. 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 trialStudying for this? GitHub Copilot free tiers and academic plans are laid out 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.