Edit Distance

Hard
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Edit Distance

Approach

Use 2D DP where each state compares prefixes. If current chars match, carry diagonal value; otherwise take min of insert/delete/replace transitions plus one.

Complexity Analysis

Time
O(m * n)
Space
O(m * n)

Pattern

2D Dynamic Programming

Why It Works

Optimal edit sequence has optimal substructure over smaller prefix pairs, which DP enumerates exhaustively.

Updated Feb 2026