Home › Company-wise questions › Microsoft › Edit Distance ← Microsoft bank
Microsoft · Question 62 · Dynamic Programming
Edit Distance Dynamic Programming Java code ⏱ O(m×n) 💾 O(m×n)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
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 Base rows/columns cost pure inserts/deletes. 2 Matches 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 Flowchart Pseudocode
Time O(m×n)Space O(m×n)Loops 4Branches 2Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat ↻ repeat yes no ↻ repeat START import java.util.* DEFINE class Main DEFINE static int minDistance(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] = i for (int j = 0; j <= n; j++) dp[0][j] = j for (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] ELSE dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j]… RETURN dp[m][n] DEFINE static void main(String[] args) java.util.Scanner sc = new java.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← Q61 · Longest Palindromic Subsequence Q63 · Decode Ways → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →