Algorithms · Visualized

DP: Edit Distance

Dynamic Programming

Break problems into overlapping subproblems and store answers.

Finds the minimum number of single-character insertions, deletions, or substitutions needed to transform one string into another. Time: O(n × m) average, O(n × m) worst; space: O(n × m), reducible to O(min(n,m)).

Big-O: The most-asked interview category — 35 classics here.

Edit Distance (Levenshtein Distance)

Dynamic Programming

Finds the minimum number of single-character insertions, deletions, or substitutions needed to transform one string into another. dp[i][j] represents the edit distance between the first i characters of one string and the first j characters of the other, built by considering the cheapest of the three possible edit operations at each step.

How Edit Distance Works

  1. Create a DP table with dimensions (len1+1) × (len2+1). Initialize dp[i][0] = i (deleting all i characters) and dp[0][j] = j (inserting all j characters) as base cases.
  2. For each pair of positions (i, j), check if the characters at string1[i-1] and string2[j-1] match.
  3. If they match, no edit is needed for this character: dp[i][j] = dp[i-1][j-1] (carry forward the cost without these characters).
  4. If they don't match, consider the three possible operations: insert (dp[i][j-1] + 1), delete (dp[i-1][j] + 1), or substitute (dp[i-1][j-1] + 1) — take the minimum of these three.
  5. Continue filling the table; dp[len1][len2] holds the minimum edit distance.

Edit Distance Worked Example

Input: {word1: horse, word2: ros}

Building the table comparing 'horse' and 'ros': characters 'r','o','s' need to align, requiring deletion of 'h', substitution of 'r' for 'o'... working through the full table, the minimum edit distance to transform 'horse' into 'ros' comes out to 3 (e.g. delete 'h', substitute 'r'→'r' [match], delete 'o' or similar sequence of 3 operations).

DP: Edit DistanceO(m·n)
Insert/delete/replace to transform strings.
·ros
·0123
h1000
o2000
r3000
s4000
e5000
h
o
r
s
e
01234
r
o
s
012
Step 1 / 17
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Edit Distance: dp[i][j] = min insert/delete/replace to turn a[0..i) into b[0..j).
Python · Dynamic Programming Algorithms in Code
def edit_distance(a, b):
    n, m = len(a), len(b)
    prev = list(range(m + 1))
    for i in range(1, n + 1):
        cur = [i] + [0] * m
        for j in range(1, m + 1):
            if a[i - 1] == b[j - 1]:
                cur[j] = prev[j - 1]
            else:
                cur[j] = 1 + min(prev[j], cur[j - 1], prev[j - 1])
        prev = cur
    return prev[m]

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Edit Distance Time & Space Complexity

BestO(n × m)
AverageO(n × m)
WorstO(n × m)
SpaceO(n × m), reducible to O(min(n,m))

When to Use Edit Distance

  • Spell checkers (suggesting corrections based on closest edit distance), DNA sequence alignment, and fuzzy string matching/search.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.