MEDIUM NC#119 Dynamic Programming

72. Edit Distance

📖 Problem

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: - Insert a character - Delete a character - Replace a character

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • Array methods (`push`, `pop`, `shift`, `slice`)
  • Object/Map/Set usage patterns
  • Function parameter and return typing
  • Array DP table updates
  • State transition thinking
  • Base case initialization

Logical Thinking Concepts

  • Define invariants before coding
  • Check edge cases first (`[]`, single element, duplicates)
  • Estimate time/space before implementation
  • Apply Dynamic Programming reasoning pattern

💡 Approach

  • Use dp[i][j] = min ops to convert word1[0:i] to word2[0:j+1]
  • If characters match: dp[i][j] = dp[i-1][j-1]
  • If they differ: dp[i][j] = min(dp[i-1][j-1] + 1, dp[i][j-1] + 1)
  • Base case: dp[0][0] = 0
  • Time: O(m * n), Space: O(m * n)

🧭 Prerequisites

🛠️ Hints & Pitfalls

Hints

  • Use dp[i][j] = min ops to convert word1[0:i] to word2[0:j+1]
  • If characters match: dp[i][j] = dp[i-1][j-1]
  • If they differ: dp[i][j] = min(dp[i-1][j-1] + 1, dp[i][j-1] + 1)

Common Pitfalls

  • Base case: dp[0][0] = 0
  • Time: O(m * n), Space: O(m * n)

🧪 Test Cases

Test Case 1
Not run
Input:
minDistance(word1: string, word2: string);
Expected:
Computed from hidden reference
Test Case 2
Not run
Input:
minDistance('horse', 'ros');
Expected:
Computed from hidden reference
Test Case 3
Not run
Input:
minDistance('intention', 'execution');
Expected:
Computed from hidden reference

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit