Uber · Question 67 · Dynamic Programming
Edit Distance (Levenshtein Distance)
Problem
Given two strings, return the minimum number of insertions, deletions, and replacements required to convert one string into the other.
Approach
DP 2D: If chars match: dp[i][j] = dp[i - 1][j - 1] Else: 1 + min(insert, delete, replace)
Time O(m×n)Space O(m×n)
How it works
- 1dp[i][j] = edits for the two prefixes.
- 2Matching chars cost nothing.
- 3Else 1 + cheapest of insert/delete/replace.
Sample input / output
Input: horse ros Output: 3
Constraints
0 <= lengths <= 500; lowercase letters only.
Solution — read it, then walk it
Time O(m×n)Space O(m×n)Loops 4Branches 3Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/23
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits