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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Collecting to Vec<char> lets you index by character, avoiding UTF-8 byte-boundary pitfalls.
- 2Edit distance only needs the previous row, so two rolling arrays replace the full O(n*m) matrix.
- 3Each cell is the cheapest of deletion, insertion, or substitution from its neighbors.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
rust
use std::f64::consts::PI; #[derive(Debug, Clone, Copy)] pub struct LatLng {
Building geographic bounding boxes in Rust
geospatial
value-types
option
Intermediate
7 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/levenshtein-distance-with-two-rows-in-rust-explained-rust-0cd8/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.