← Microsoft bank

Microsoft · Question 62 · Dynamic Programming

Edit Distance

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

Problem

Return min operations to convert word1 to word2 (insert, delete, replace).

Approach

Classic 2D DP over both prefixes.

Time O(m×n)Space O(m×n)

How it works

  1. 1Base rows/columns cost pure inserts/deletes.
  2. 2Matches are free; else 1 + cheapest edit.

Sample input / output

Input:
horse
ros
Output:
3

Constraints

0 <= lengths <= 500; lowercase only.

Solution — read it, then walk it

Time O(m×n)Space O(m×n)Loops 4Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatyesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intminDistance(String word1,String word2)DEFINE m = word1.length(),n = word2.length()DEFINE [][] dp = new int[m+ 1][n + 1]for (int i = 0; i <=m; i++)dp[i][0] = ifor (int j = 0; j <=n; j++)dp[0][j] = jfor (int i = 1; i <=m; i++)for (int j = 1; j <=n; j++)if (word1.charAt(i -1) == word2.charAt(j -1))dp[i][j] = dp[i - 1][j - 1]ELSEdp[i][j] = 1 +Math.min(dp[i - 1][j - 1],Math.min(dp[i - 1][j]…RETURN dp[m][n]DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)String w1 = sc.next();String w2 = sc.next()System.out.println(minDistance(w1,w2))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/21

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