</>

72. Edit Distance

Medium NeetCode 150
2-D Dynamic Programming Time O(M*N) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
2-D Dynamic Programming
Time
O(M*N)
Space
O(N)

Standard Solution (C++)

SummaryGiven two strings, find the minimum number of single-character operations (insert, delete, or replace) required to transform one string into the other.

Approach
  • Build a 2-D DP table where dp[i][j] = min edits to convert word1[0..i-1] to word2[0..j-1].
  • Base cases: converting an empty string to a length-k string costs exactly k operations.
  • If the current characters match, no new edit is needed: dp[i][j] = dp[i-1][j-1]; otherwise take the minimum of insert (dp[i][j-1]), delete (dp[i-1][j]), and replace (dp[i-1][j-1]) and add 1.
  • Space can be compressed to two 1-D rows (or one row with a saved diagonal) since each cell only depends on the row above and the column to the left.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size(), n = word2.size();

        // dp[j] = min edits to convert word1[0..j-1] -> word2[0..i-1]
        // Initialize for i == 0: cost is j deletions from word1.
        vector<int> dp(m + 1);
        for (int j = 0; j <= m; ++j) dp[j] = j;

        for (int i = 1; i <= n; ++i) {
            int diag = dp[0];   // dp[i-1][j-1] before overwrite
            dp[0] = i;          // base case: i insertions to reach word2[0..i-1] from ""

            for (int j = 1; j <= m; ++j) {
                int saved = dp[j]; // will become diag for next column
                if (word2[i - 1] == word1[j - 1]) {
                    // Characters match — carry the diagonal value unchanged.
                    dp[j] = diag;
                } else {
                    // Replace (diag), insert into word1 (dp[j-1]),
                    // delete from word1 (dp[j]) — pick the cheapest.
                    dp[j] = 1 + min({diag, dp[j - 1], dp[j]});
                }
                diag = saved;
            }
        }

        return dp[m];
    }
};
Time O(m * n) Space O(m)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int minDistance(string word1, string word2) {
        // - - h o r s e (len1)
        // - 0 1 2 3 4 5
        // r 1
        // o 2
        // s 3
        // (len2)

        int len1=word1.size();
        int len2=word2.size();

        vector<int> dp(len1+1, 0);

        // init dp
        for(int j=0; j<=len1; ++j){
            dp[j]=j;
        }

        for(int i=1; i<=len2; ++i){
            int prev_diag=dp[0]; // record prev[j-1]
            int tmp=0;
            
            dp[0]=i;
            for(int j=1; j<=len1; ++j){
                tmp=dp[j];
                if(word1[j-1]==word2[i-1]){
                    dp[j]=prev_diag;
                }
                else{
                    dp[j]=std::min(dp[j-1], std::min(prev_diag, dp[j]))+1;
                }
                prev_diag=tmp;
            }
        }

        return dp[len1];
    }
};

// Time Complexity: O(M*N)
// Space Complexity: O(N)
Time O(M*N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern