MEDIUM Dynamic Programming 2D

583. Delete Operation for Two Strings

📖 Problem

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same, where each step can delete one character in either string.

🧠 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

  • dp[i][j] = min deletions to make word1[0:i] and word2[0:j] equal
  • If chars match: dp[i][j] = dp[i-1][j-1]
  • If chars don't match: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])
  • Time: O(m * n), Space: O(m * n) where m, n = lengths
  • 2*LCS, Space-optimized DP

🛠️ Hints & Pitfalls

Hints

  • dp[i][j] = min deletions to make word1[0:i] and word2[0:j] equal
  • If chars match: dp[i][j] = dp[i-1][j-1]
  • If chars don't match: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])

Common Pitfalls

  • Time: O(m * n), Space: O(m * n) where m, n = lengths
  • 2*LCS, Space-optimized DP

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
minDistance('sea', 'eat');
Expected:
2
Test Case 2
Not run
Input:
minDistance('leetcode', 'etco');
Expected:
4
Test Case 3
Not run
Input:
minDistance('a', 'b');
Expected:
2

📝 Code Editor

📚 Reference Solution

⌘K Search ⌘↩ Run ⌘S Submit