rust 27 lines · 6 steps

Levenshtein distance with two rows in Rust

Computes edit distance between two strings using rolling rows instead of a full matrix.

Explained by highlit
1pub fn levenshtein(a: &str, b: &str) -> usize {
2 let a: Vec<char> = a.chars().collect();
3 let b: Vec<char> = b.chars().collect();
4 
5 if a.is_empty() {
6 return b.len();
7 }
8 if b.is_empty() {
9 return a.len();
10 }
11 
12 let mut prev: Vec<usize> = (0..=b.len()).collect();
13 let mut curr = vec![0usize; b.len() + 1];
14 
15 for (i, &ca) in a.iter().enumerate() {
16 curr[0] = i + 1;
17 for (j, &cb) in b.iter().enumerate() {
18 let cost = if ca == cb { 0 } else { 1 };
19 curr[j + 1] = (prev[j + 1] + 1)
20 .min(curr[j] + 1)
21 .min(prev[j] + cost);
22 }
23 std::mem::swap(&mut prev, &mut curr);
24 }
25 
26 prev[b.len()]
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Collecting to Vec<char> lets you index by character, avoiding UTF-8 byte-boundary pitfalls.
  2. 2Edit distance only needs the previous row, so two rolling arrays replace the full O(n*m) matrix.
  3. 3Each cell is the cheapest of deletion, insertion, or substitution from its neighbors.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Levenshtein distance with two rows in Rust — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code