What is Edit Distance
Levenshtein distance is the fewest insertions, deletions, and replacements that turn s into t. dp[i][j] solves prefixes s[:i] and t[:j].
Brute force approach
Insert, delete, or replace is three recursive branches. The pair of indexes is solved many times. Memoization stores the distance for each pair.
Each string is at most 2 letters so the recursion tree fits the canvas. horse to ros is the longer practice case.
Memoized approach
dp[i][j] is the distance of the two prefixes. Equal letters copy the diagonal; else 1 + min of the three edits.Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
horse, t = ros. Three edits: replace h→r, delete r, replace e→s. Step through the DP table. The live code on the right is the DP recurrence — brute force is shown in Implementations below so you can see why it TLE.Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each cell | O(1) |
| Fill table | O(mn) |
| Space | O(mn) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations