← Uber bank

Uber · Question 67 · Dynamic Programming

Edit Distance (Levenshtein Distance)

Dynamic ProgrammingPythoncode⏱ O(m×n)💾 O(m×n)
Product-based

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

  1. 1dp[i][j] = edits for the two prefixes.
  2. 2Matching chars cost nothing.
  3. 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.
↻ repeat↻ repeat↻ repeatyesno↻ repeatyesnoSTARTword1, word2m, n = len(word1),len(word2)dp = [[0] * (n + 1) for _in range(m + 1)]for i in range(m + 1)dp[i][0] = ifor j in range(n + 1)dp[0][j] = jfor i in range(1, m +1)for j in range(1, n +1)if word1[i - 1] ==word2[j - 1]dp[i][j] = dp[i - 1][j - 1]ELSEdp[i][j] = 1 + min(dp[i -1][j], dp[i][j - 1], dp[i -1][j - 1])RETURN dp[m][n]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)word1 = next(it); word2 =next(it)print(minDistance(word1,word2))if __name__ =="__main__"main()END
  • 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