← All Exercises

Edit Distance with Rolling DP

advancedtypescript~25min

Background

Edit distance drives diff tools, spell correction, fuzzy matching, and DNA sequence alignment.

Problem

Given two strings, return the minimum number of single-character insertions, deletions, and substitutions needed to turn the first into the second.

Input

Two strings, each up to 2000 characters, possibly empty.

Output

A non-negative integer representing the minimum edit count.

Sample tests

Sample 1

Input: a = "kitten", b = "sitting"
Expected: 3

Sample 2

Input: a = "horse", b = "ros"
Expected: 3

Sample 3

Input: a = "", b = "abc"
Expected: 3

Your solution

Learning objective

Compress a two-dimensional edit-distance table into one row while tracking the diagonal dependency.