Skip to content

14.6   Edit distance problem

Edit distance, also called Levenshtein distance, is the minimum number of edits needed to transform one string into another. It is commonly used in information retrieval and natural language processing to measure similarity between sequences.

Question

Given two strings \(s\) and \(t\), return the minimum number of edits needed to transform \(s\) into \(t\).

Three edits are allowed: insert a character, delete a character, or replace a character with any other character.

As shown in Figure 14-27, transforming kitten into sitting takes 3 edits: 2 replacements and 1 insertion. Transforming hello into algo also takes 3 edits: 2 replacements and 1 deletion.

Figure 14-27   Examples of edit distance

Description of Figure 14-27: Edit distance: two three-step transformation examples

The alignments show how kitten becomes sitting and how hello becomes algo. Each transformation takes at least 3 edits, and the examples achieve that minimum.

Each edit may insert, delete, or replace one character.

The figure places two character-by-character alignment diagrams side by side; from top to bottom, each shows the source string row, an intermediate edited row, and the target string row. In both diagrams, arrows indicate the edit type and positional correspondence at each character without prescribing a unique order for the three edits.

On the left, source string s = kitten is transformed into target string t = sitting: the first letter k is replaced with s (blue), the 5th letter e is replaced with i (blue), and the letter g is inserted at the end (purple); the other 4 unchanged letters i, t, t, and n remain as they are, with vertical dashed lines aligning the intermediate row to the target row. The intermediate row reads s, i, t, t, i, n, g, with the replacements s and i in blue and the inserted g in purple, already matching the target string. Counting characters, the length changes from 6 to 7.

On the right, source string s = hello is transformed into target string t = algo: the first letter h is deleted (shown faded in light orange in the intermediate row and not carried down into the target string), the 2nd letter e is replaced with a (blue), and the second of the two consecutive l letters is replaced with g (blue), while the first l and the final o remain unchanged, with vertical dashed lines aligning the intermediate row to the target row. The intermediate row keeps the faded h followed by a, l, g, o, whereas the target row keeps only a, l, g, o. Counting characters, the length changes from 5 to 4.

Edits in the two examples
SourceTargetReplacementsInsertion or deletionEdits
kittensittingk → s; e → iInsert g at end3
helloalgoe → a; second l → gDelete leading h3

The drawing does not label the total edit count directly; the count of 3 in the table comes from adding two replacements and one insertion or deletion in each example, matching the minimum number of edits stated in the text.

Edit distance fits naturally into a decision tree model. Strings are nodes, and each decision (an edit) is an edge.

As shown in Figure 14-28, without restrictions on the edits, each node can have many outgoing edges, one for each possible operation. Thus, many paths can transform hello into algo.

From the decision tree perspective, the goal is to find the shortest path between nodes hello and algo.

Figure 14-28   Edit distance as a decision tree

Description of Figure 14-28: Decision tree for edit distance

Modeling strings as nodes and single edits as directed edges frames the problem as finding the shortest path from hello to algo in a decision tree; the figure expands one three-step transformation path while leaving other branches unexpanded.

In the decision tree model, each node represents a string state, and each outgoing directed edge represents one decision (a single insertion, deletion, or replacement operation). Finding the edit distance from string s = hello to t = algo is equivalent to finding the shortest path from the root node hello to the target node algo in this decision tree.

From top to bottom on the left, the figure expands a single path of 4 string nodes and 3 directed edges, starting from s = hello at the top and ending at t = algo at the bottom. The table below lists each edge and its operation in order; the first edge in the drawing reads only "Replace l with g," and "the second l" is added by comparing the two node strings to clarify the position.

To the right of each expanded node in the top three levels (hello, helgo, and halgo), 3 additional branch arrows point to ellipses "...", indicating that without restrictions on edits, every string can branch into many other edit choices; those abbreviated branches omit specific strings, since the figure illustrates the shortest-path perspective on the decision tree rather than exhausting the entire search tree.

Edits along the expanded path
Starting stringOperationResulting string
helloReplace the second l with ghelgo
helgoReplace e with ahalgo
halgoDelete the leading halgo

This path reaches algo from hello in 3 edits, matching the edit distance of 3 shown in Figure 14-27 earlier in this section. Examining this single expanded path only confirms that 3 edits suffice; by itself, it cannot rule out a shorter path.

1.   Dynamic programming approach

Step 1: Identify each decision, define the state, and establish the \(dp\) table

Each decision applies one edit to string \(s\).

We want each edit to reduce the problem's size so that we can form subproblems. Let the lengths of \(s\) and \(t\) be \(n\) and \(m\). First consider their last characters, \(s[n-1]\) and \(t[m-1]\).

  • If \(s[n-1]\) and \(t[m-1]\) match, skip them and consider \(s[n-2]\) and \(t[m-2]\).
  • If \(s[n-1]\) and \(t[m-1]\) differ, apply an edit to \(s\) (insertion, deletion, or replacement) to match the endings, allowing us to move on to a smaller problem.

Each decision (edit) in \(s\) changes the characters still to be matched in \(s\) and \(t\). The state therefore specifies the \(i\)-th and \(j\)-th characters currently under consideration in \(s\) and \(t\), denoted by \([i, j]\).

State \([i, j]\) represents the subproblem of finding the minimum number of edits needed to transform the first \(i\) characters of \(s\) into the first \(j\) characters of \(t\).

This gives a two-dimensional \(dp\) table of size \((n+1) \times (m+1)\).

Step 2: Identify optimal substructure and derive the state transition equation

For subproblem \(dp[i, j]\), the final characters are \(s[i-1]\) and \(t[j-1]\). The three possible edits give the cases shown in Figure 14-29.

  1. Insert \(t[j-1]\) after \(s[i-1]\), leaving subproblem \(dp[i, j-1]\).
  2. Delete \(s[i-1]\), leaving subproblem \(dp[i-1, j]\).
  3. Replace \(s[i-1]\) with \(t[j-1]\), leaving subproblem \(dp[i-1, j-1]\).

Figure 14-29   State transitions for edit distance

Description of Figure 14-29: State transitions for edit distance

When transforming book into code, the last characters k and e differ. Insertion, deletion, and replacement each leave a different pair of prefixes to transform.

Let state dp[i, j] be the minimum number of edits needed to transform the first i characters of source string s into the first j characters of target string t, where each insertion, deletion, or replacement costs 1. Using s = book and t = code (current prefix lengths i = 4 and j = 4), this figure examines where the state transitions come from when the current final characters s[i-1] = k and t[j-1] = e differ.

On the left is the current state dp[i, j], and on the right from top to bottom are the three branches for insertion (appending), deletion, and replacement. Grayed-out final characters indicate characters already matched or deleted and no longer part of the remaining prefixes to be solved.

After insertion, the newly appended final character matches and cancels the target's final character without consuming any character of the original source string, so only j decreases by 1. Deletion removes only the source's final character, so only i decreases by 1. After replacement, the two final characters match and cancel each other, so both i and j decrease by 1.

Following the three branches in order, the table below distinguishes "Source after edit" from "Remaining source prefix" and lists the corresponding subproblem state; the figure does not compute the final edit distance from book to code.

Three operations and remaining prefixes when the final characters differ
OperationSource after editRemaining source prefixRemaining target prefixSubproblem state
Insert ebookebookcoddp[i,j-1]
Delete kbooboocodedp[i-1,j]
Replace k with ebooeboocoddp[i-1,j-1]

Each of the three operations costs 1 edit, and we choose whichever leaves the fewest edits in its remaining subproblem; therefore, when the final characters differ, dp[i,j] = min(dp[i,j-1], dp[i-1,j], dp[i-1,j-1]) + 1.

The optimal substructure follows: the minimum edit count \(dp[i, j]\) is the smallest of \(dp[i, j-1]\), \(dp[i-1, j]\), and \(dp[i-1, j-1]\), plus \(1\) for the current edit. The state transition equation is:

\[ dp[i, j] = \min(dp[i, j-1], dp[i-1, j], dp[i-1, j-1]) + 1 \]

When \(s[i-1]\) and \(t[j-1]\) match, no edit is needed for the current characters, and the state transition equation becomes:

\[ dp[i, j] = dp[i-1, j-1] \]

Step 3: Determine the boundary conditions and evaluation order

If both strings are empty, \(0\) edits are needed, so \(dp[0, 0] = 0\). If \(s\) is empty but \(t\) is not, the minimum edit count is the length of \(t\), giving the first row \(dp[0, j] = j\). If \(s\) is nonempty but \(t\) is empty, the count is the length of \(s\), giving the first column \(dp[i, 0] = i\).

The solution \(dp[i, j]\) depends on entries to its left, above, and upper left, so two nested loops can traverse the \(dp\) table in increasing index order.

2.   Code implementation

edit_distance.py
def edit_distance_dp(s: str, t: str) -> int:
    """Edit distance: dynamic programming"""
    n, m = len(s), len(t)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    # State transitions: first row and first column
    for i in range(1, n + 1):
        dp[i][0] = i
    for j in range(1, m + 1):
        dp[0][j] = j
    # State transitions: remaining rows and columns
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if s[i - 1] == t[j - 1]:
                # If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1]
            else:
                # Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1
    return dp[n][m]
edit_distance.cpp
/* Edit distance: dynamic programming */
int editDistanceDP(string s, string t) {
    int n = s.length(), m = t.length();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    // State transitions: first row and first column
    for (int i = 1; i <= n; i++) {
        dp[i][0] = i;
    }
    for (int j = 1; j <= m; j++) {
        dp[0][j] = j;
    }
    // State transitions: remaining rows and columns
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
            }
        }
    }
    return dp[n][m];
}
edit_distance.java
/* Edit distance: dynamic programming */
int editDistanceDP(String s, String t) {
    int n = s.length(), m = t.length();
    int[][] dp = new int[n + 1][m + 1];
    // State transitions: first row and first column
    for (int i = 1; i <= n; i++) {
        dp[i][0] = i;
    }
    for (int j = 1; j <= m; j++) {
        dp[0][j] = j;
    }
    // State transitions: remaining rows and columns
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (s.charAt(i - 1) == t.charAt(j - 1)) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
            }
        }
    }
    return dp[n][m];
}
edit_distance.cs
/* Edit distance: dynamic programming */
int EditDistanceDP(string s, string t) {
    int n = s.Length, m = t.Length;
    int[,] dp = new int[n + 1, m + 1];
    // State transitions: first row and first column
    for (int i = 1; i <= n; i++) {
        dp[i, 0] = i;
    }
    for (int j = 1; j <= m; j++) {
        dp[0, j] = j;
    }
    // State transitions: remaining rows and columns
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[i, j] = dp[i - 1, j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i, j] = Math.Min(Math.Min(dp[i, j - 1], dp[i - 1, j]), dp[i - 1, j - 1]) + 1;
            }
        }
    }
    return dp[n, m];
}
edit_distance.go
/* Edit distance: dynamic programming */
func editDistanceDP(s string, t string) int {
    n := len(s)
    m := len(t)
    dp := make([][]int, n+1)
    for i := 0; i <= n; i++ {
        dp[i] = make([]int, m+1)
    }
    // State transitions: first row and first column
    for i := 1; i <= n; i++ {
        dp[i][0] = i
    }
    for j := 1; j <= m; j++ {
        dp[0][j] = j
    }
    // State transitions: remaining rows and columns
    for i := 1; i <= n; i++ {
        for j := 1; j <= m; j++ {
            if s[i-1] == t[j-1] {
                // If the two bytes are equal, skip both (each byte is one character for ASCII input)
                dp[i][j] = dp[i-1][j-1]
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = MinInt(MinInt(dp[i][j-1], dp[i-1][j]), dp[i-1][j-1]) + 1
            }
        }
    }
    return dp[n][m]
}
edit_distance.swift
/* Edit distance: dynamic programming */
func editDistanceDP(s: String, t: String) -> Int {
    let n = s.utf8CString.count
    let m = t.utf8CString.count
    var dp = Array(repeating: Array(repeating: 0, count: m + 1), count: n + 1)
    // State transitions: first row and first column
    for i in 1 ... n {
        dp[i][0] = i
    }
    for j in 1 ... m {
        dp[0][j] = j
    }
    // State transitions: remaining rows and columns
    for i in 1 ... n {
        for j in 1 ... m {
            if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
                // If the two current UTF-8 bytes match, skip both
                dp[i][j] = dp[i - 1][j - 1]
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
            }
        }
    }
    return dp[n][m]
}
edit_distance.js
/* Edit distance: dynamic programming */
function editDistanceDP(s, t) {
    const n = s.length,
        m = t.length;
    const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
    // State transitions: first row and first column
    for (let i = 1; i <= n; i++) {
        dp[i][0] = i;
    }
    for (let j = 1; j <= m; j++) {
        dp[0][j] = j;
    }
    // State transitions: remaining rows and columns
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= m; j++) {
            if (s.charAt(i - 1) === t.charAt(j - 1)) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] =
                    Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
            }
        }
    }
    return dp[n][m];
}
edit_distance.ts
/* Edit distance: dynamic programming */
function editDistanceDP(s: string, t: string): number {
    const n = s.length,
        m = t.length;
    const dp = Array.from({ length: n + 1 }, () =>
        Array.from({ length: m + 1 }, () => 0)
    );
    // State transitions: first row and first column
    for (let i = 1; i <= n; i++) {
        dp[i][0] = i;
    }
    for (let j = 1; j <= m; j++) {
        dp[0][j] = j;
    }
    // State transitions: remaining rows and columns
    for (let i = 1; i <= n; i++) {
        for (let j = 1; j <= m; j++) {
            if (s.charAt(i - 1) === t.charAt(j - 1)) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] =
                    Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
            }
        }
    }
    return dp[n][m];
}
edit_distance.dart
/* Edit distance: dynamic programming */
int editDistanceDP(String s, String t) {
  int n = s.length, m = t.length;
  List<List<int>> dp = List.generate(n + 1, (_) => List.filled(m + 1, 0));
  // State transitions: first row and first column
  for (int i = 1; i <= n; i++) {
    dp[i][0] = i;
  }
  for (int j = 1; j <= m; j++) {
    dp[0][j] = j;
  }
  // State transitions: remaining rows and columns
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= m; j++) {
      if (s[i - 1] == t[j - 1]) {
        // If the two characters are equal, skip both of them
        dp[i][j] = dp[i - 1][j - 1];
      } else {
        // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
        dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
      }
    }
  }
  return dp[n][m];
}
edit_distance.rs
/* Edit distance: dynamic programming */
fn edit_distance_dp(s: &str, t: &str) -> i32 {
    let (n, m) = (s.len(), t.len());
    let mut dp = vec![vec![0; m + 1]; n + 1];
    // State transitions: first row and first column
    for i in 1..=n {
        dp[i][0] = i as i32;
    }
    for j in 1..m {
        dp[0][j] = j as i32;
    }
    // State transitions: remaining rows and columns
    for i in 1..=n {
        for j in 1..=m {
            if s.chars().nth(i - 1) == t.chars().nth(j - 1) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] =
                    std::cmp::min(std::cmp::min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
            }
        }
    }
    dp[n][m]
}
edit_distance.c
/* Edit distance: dynamic programming */
int editDistanceDP(char *s, char *t, int n, int m) {
    int **dp = malloc((n + 1) * sizeof(int *));
    for (int i = 0; i <= n; i++) {
        dp[i] = calloc(m + 1, sizeof(int));
    }
    // State transitions: first row and first column
    for (int i = 1; i <= n; i++) {
        dp[i][0] = i;
    }
    for (int j = 1; j <= m; j++) {
        dp[0][j] = j;
    }
    // State transitions: remaining rows and columns
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = myMin(myMin(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
            }
        }
    }
    int res = dp[n][m];
    // Free memory
    for (int i = 0; i <= n; i++) {
        free(dp[i]);
    }
    return res;
}
edit_distance.kt
/* Edit distance: dynamic programming */
fun editDistanceDP(s: String, t: String): Int {
    val n = s.length
    val m = t.length
    val dp = Array(n + 1) { IntArray(m + 1) }
    // State transitions: first row and first column
    for (i in 1..n) {
        dp[i][0] = i
    }
    for (j in 1..m) {
        dp[0][j] = j
    }
    // State transitions: remaining rows and columns
    for (i in 1..n) {
        for (j in 1..m) {
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[i][j] = dp[i - 1][j - 1]
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[i][j] = min(min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1
            }
        }
    }
    return dp[n][m]
}
edit_distance.rb
### Edit distance: dynamic programming ###
def edit_distance_dp(s, t)
  n, m = s.length, t.length
  dp = Array.new(n + 1) { Array.new(m + 1, 0) }
  # State transitions: first row and first column
  (1...(n + 1)).each { |i| dp[i][0] = i }
  (1...(m + 1)).each { |j| dp[0][j] = j }
  # State transitions: remaining rows and columns
  for i in 1...(n + 1)
    for j in 1...(m +1)
      if s[i - 1] == t[j - 1]
        # If the two characters are equal, skip both of them
        dp[i][j] = dp[i - 1][j - 1]
      else
        # Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
        dp[i][j] = [dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]].min + 1
      end
    end
  end
  dp[n][m]
end
Visualize execution

As shown in Figure 14-30, the state transition process resembles that of the knapsack problem: both fill a two-dimensional grid.

Figure 14-30   Dynamic programming for edit distance

Description of Figure 14-30: Dynamic programming for edit distance

Fill the table cell by cell across source and target prefixes to find the minimum number of edits needed to transform string bag into pack.

The source string s is bag (length 3), and the target string t is pack (length 4); note that this input differs from the other examples in the text. Each operation inserts, deletes, or replaces a single character at a cost of 1.

State dp[i, j] represents the minimum number of edits needed to transform the first i characters of source string s (the source prefix) into the first j characters of target string t (the target prefix). The two-dimensional table has 4 rows and 5 columns: rows i = 0 to 3 correspond to source prefixes empty string, b, ba, and bag; columns j = 0 to 4 correspond to target prefixes empty string, p, pa, pac, and pack.

First create a 4×5 all-zero table, in which dp[0, 0] is already the valid boundary value 0 for transforming one empty string into another; then initialize the positive-length entries in the first row as dp[0, j] = j (inserting j characters into the empty string to form the target prefix) and in the first column as dp[i, 0] = i (deleting i characters from the source prefix to reach the empty string). The remaining 12 interior cells are solved row by row from top to bottom, and from left to right within each row.

To compute dp[i, j], compare the final character s[i - 1] of the current source prefix with the final character t[j - 1] of the target prefix: if the two final characters match, no additional edit is needed, so the entry equals the upper-left value dp[i - 1, j - 1] directly (without adding 1); if they differ, take the minimum of the left entry dp[i, j - 1] (insertion), the upper entry dp[i - 1, j] (deletion), and the upper-left entry dp[i - 1, j - 1] (replacement), plus 1. Each step provides a uniquely named full state table marking every cell's value together with "valid boundary," "computed," or "uncomputed initial value"; step 15 marks the bottom-right cell as "return value." Row and column headers give both i or j and the corresponding prefix for lookup either by coordinates or by prefix.

  1. Create the initial 4×5 all-zero dp table

    For source string s = bag (length 3) and target string t = pack (length 4), create a 4×5 two-dimensional dp table. All 20 cells currently hold 0: dp[0, 0] is already the valid boundary for transforming an empty string into an empty string, while the remaining 19 cells hold uncomputed initial values, with the positive-length boundaries in the first row and first column yet to be set.

    Edit distance, step 1: full all-zero dp table
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=1, b0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=2, ba0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  2. Initialize the empty-string boundaries in the first row and first column

    Keep dp[0, 0] = 0 for transforming an empty string into an empty string. Initialize the first row from dp[0, 0] to dp[0, 4] as [0, 1, 2, 3, 4] (transforming the empty source prefix into the length-j target prefixes empty string, p, pa, pac, and pack requires inserting j characters, with dp[0, 4] = 4 for empty string to pack); initialize the first column from dp[0, 0] to dp[3, 0] as [0, 1, 2, 3] (transforming the length-i source prefixes empty string, b, ba, and bag into the empty string requires deleting i characters, with dp[3, 0] = 3 for bag to empty string). In the interior, across rows 1 to 3 and columns 1 to 4, the 12 entries of 0 remain uncomputed initial values.

    Edit distance, step 2: full dp table after initializing empty-string boundaries
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=2, ba2, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  3. Compute dp[1, 1] (source prefix b to target prefix p): minimum 1 edit

    At i = 1, j = 1, compute dp[1, 1] for transforming source prefix b into target prefix p: the source final character b and target final character p differ, so compare left dp[1, 0] = 1, above dp[0, 1] = 1, and upper-left dp[0, 0] = 0, take the minimum 0 plus 1 (corresponding to replacing b with p), and write dp[1, 1] = 1.

    Edit distance, step 3: full dp table after computing dp[1, 1]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=2, ba2, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  4. Compute dp[1, 2] (source prefix b to target prefix pa): minimum 2 edits

    At i = 1, j = 2, compute dp[1, 2] for transforming source prefix b into target prefix pa: the source final character b and target final character a differ, so compare left dp[1, 1] = 1, above dp[0, 2] = 2, and upper-left dp[0, 1] = 1, take the minimum 1 plus 1, and write dp[1, 2] = 2.

    Edit distance, step 4: full dp table after computing dp[1, 2]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed0, uncomputed initial value0, uncomputed initial value
    i=2, ba2, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  5. Compute dp[1, 3] (source prefix b to target prefix pac): minimum 3 edits

    At i = 1, j = 3, compute dp[1, 3] for transforming source prefix b into target prefix pac: the source final character b and target final character c differ, so compare left dp[1, 2] = 2, above dp[0, 3] = 3, and upper-left dp[0, 2] = 2, take the minimum 2 plus 1, and write dp[1, 3] = 3.

    Edit distance, step 5: full dp table after computing dp[1, 3]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed0, uncomputed initial value
    i=2, ba2, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  6. Compute dp[1, 4] (source prefix b to target string pack): minimum 4 edits

    At i = 1, j = 4, compute dp[1, 4] for transforming source prefix b into the full target string pack: the source final character b and target final character k differ, so compare left dp[1, 3] = 3, above dp[0, 4] = 4, and upper-left dp[0, 3] = 3, take the minimum 3 plus 1, and write dp[1, 4] = 4, completing row 1.

    Edit distance, step 6: full dp table after computing dp[1, 4]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  7. Compute dp[2, 1] (source prefix ba to target prefix p): minimum 2 edits

    Move to row 2 and process i = 2, j = 1 to compute dp[2, 1] for transforming source prefix ba into target prefix p: the source final character a and target final character p differ, so compare left dp[2, 0] = 2, above dp[1, 1] = 1, and upper-left dp[1, 0] = 1, take the minimum 1 plus 1, and write dp[2, 1] = 2.

    Edit distance, step 7: full dp table after computing dp[2, 1]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  8. Compute dp[2, 2] (source prefix ba to target prefix pa): both end in a, take 1 directly

    At i = 2, j = 2, compute dp[2, 2] for transforming source prefix ba into target prefix pa: the current source prefix final character s[1] and target prefix final character t[1] are both a, so the two final characters match completely and need no additional edit; instead of adding 1 to the result for b to p, copy upper-left dp[1, 1] = 1 directly and write dp[2, 2] = 1.

    Edit distance, step 8: full dp table after computing dp[2, 2]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed0, uncomputed initial value0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  9. Compute dp[2, 3] (source prefix ba to target prefix pac): minimum 2 edits

    At i = 2, j = 3, compute dp[2, 3] for transforming source prefix ba into target prefix pac: the source final character a and target final character c differ, so compare left dp[2, 2] = 1, above dp[1, 3] = 3, and upper-left dp[1, 2] = 2, take the minimum from the left, 1 (inserting c on top of the 1-edit transformation from ba to pa), plus 1, and write dp[2, 3] = 2.

    Edit distance, step 9: full dp table after computing dp[2, 3]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed0, uncomputed initial value
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  10. Compute dp[2, 4] (source prefix ba to target string pack): minimum 3 edits

    At i = 2, j = 4, compute dp[2, 4] for transforming source prefix ba into the full target string pack: the source final character a and target final character k differ, so compare left dp[2, 3] = 2, above dp[1, 4] = 4, and upper-left dp[1, 3] = 3, take the minimum from the left, 2, plus 1, and write dp[2, 4] = 3, completing row 2.

    Edit distance, step 10: full dp table after computing dp[2, 4]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed3, computed
    i=3, bag3, valid boundary0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  11. Compute dp[3, 1] (source string bag to target prefix p): minimum 3 edits

    Move to row 3 and process i = 3, j = 1 to compute dp[3, 1] for transforming the full source string bag into target prefix p: the source final character g and target final character p differ, so compare left dp[3, 0] = 3, above dp[2, 1] = 2, and upper-left dp[2, 0] = 2, take the minimum 2 plus 1, and write dp[3, 1] = 3.

    Edit distance, step 11: full dp table after computing dp[3, 1]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed3, computed
    i=3, bag3, valid boundary3, computed0, uncomputed initial value0, uncomputed initial value0, uncomputed initial value
  12. Compute dp[3, 2] (source string bag to target prefix pa): minimum 2 edits

    At i = 3, j = 2, compute dp[3, 2] for transforming the full source string bag into target prefix pa: the source final character g and target final character a differ, so compare left dp[3, 1] = 3, above dp[2, 2] = 1, and upper-left dp[2, 1] = 2, take the minimum from above, 1 (deleting the final g leaves the subproblem of converting ba to pa), plus 1, and write dp[3, 2] = 2.

    Edit distance, step 12: full dp table after computing dp[3, 2]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed3, computed
    i=3, bag3, valid boundary3, computed2, computed0, uncomputed initial value0, uncomputed initial value
  13. Compute dp[3, 3] (source string bag to target prefix pac): minimum 2 edits

    At i = 3, j = 3, compute dp[3, 3] for transforming the full source string bag into target prefix pac: the source final character g and target final character c differ, so compare left dp[3, 2] = 2, above dp[2, 3] = 2, and upper-left dp[2, 2] = 1, take the upper-left minimum, 1 (once the final g is replaced by c, the remaining subproblem is to convert ba to pa), plus 1, and write dp[3, 3] = 2.

    Edit distance, step 13: full dp table after computing dp[3, 3]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed3, computed
    i=3, bag3, valid boundary3, computed2, computed2, computed0, uncomputed initial value
  14. Compute dp[3, 4] (source string bag to target string pack): minimum 3 edits

    At the bottom-right cell i = 3, j = 4, compute dp[3, 4] for transforming the full source string bag into the full target string pack: the source final character g and target final character k differ, so compare left dp[3, 3] = 2, above dp[2, 4] = 3, and upper-left dp[2, 3] = 2, take the minimum 2 plus 1, and write dp[3, 4] = 3, completing the entire table.

    Edit distance, step 14: full dp table after computing dp[3, 4]
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed3, computed
    i=3, bag3, valid boundary3, computed2, computed2, computed3, computed
  15. Read bottom-right dp[3, 4] and return the minimum edit count 3

    After all state transitions finish, highlight the bottom-right entry dp[3, 4] = 3 and return it as the minimum number of edits needed to transform the full source string bag into the full target string pack. No other cells are updated in this step; the table gives the minimum edit count without specifying a unique sequence of edits.

    Edit distance, step 15: full dp table returning the final result
    Source prefix / target prefixj=0, empty stringj=1, pj=2, paj=3, pacj=4, pack
    i=0, empty string0, valid boundary1, valid boundary2, valid boundary3, valid boundary4, valid boundary
    i=1, b1, valid boundary1, computed2, computed3, computed4, computed
    i=2, ba2, valid boundary2, computed1, computed2, computed3, computed
    i=3, bag3, valid boundary3, computed2, computed2, computed3, return value

3.   Space optimization

The state \(dp[i,j]\) depends on \(dp[i-1, j]\) above, \(dp[i, j-1]\) to the left, and \(dp[i-1, j-1]\) at the upper left. Forward iteration loses \(dp[i-1, j-1]\), while backward iteration cannot compute \(dp[i, j-1]\) in advance. Neither order alone is sufficient.

We can use a variable leftup to preserve the upper-left solution \(dp[i-1, j-1]\), leaving only the left and upper entries to consider. The situation then matches unbounded knapsack, and forward iteration works. The code is as follows:

edit_distance.py
def edit_distance_dp_comp(s: str, t: str) -> int:
    """Edit distance: space-optimized dynamic programming"""
    n, m = len(s), len(t)
    dp = [0] * (m + 1)
    # State transitions: first row
    for j in range(1, m + 1):
        dp[j] = j
    # State transitions: remaining rows
    for i in range(1, n + 1):
        # State transitions: first column
        leftup = dp[0]  # Temporarily store dp[i-1, j-1]
        dp[0] += 1
        # State transitions: remaining columns
        for j in range(1, m + 1):
            temp = dp[j]
            if s[i - 1] == t[j - 1]:
                # If the two characters are equal, skip both of them
                dp[j] = leftup
            else:
                # Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = min(dp[j - 1], dp[j], leftup) + 1
            leftup = temp  # Update to dp[i-1, j-1] for the next iteration
    return dp[m]
edit_distance.cpp
/* Edit distance: space-optimized dynamic programming */
int editDistanceDPComp(string s, string t) {
    int n = s.length(), m = t.length();
    vector<int> dp(m + 1, 0);
    // State transitions: first row
    for (int j = 1; j <= m; j++) {
        dp[j] = j;
    }
    // State transitions: remaining rows
    for (int i = 1; i <= n; i++) {
        // State transitions: first column
        int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i;
        // State transitions: remaining columns
        for (int j = 1; j <= m; j++) {
            int temp = dp[j];
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m];
}
edit_distance.java
/* Edit distance: space-optimized dynamic programming */
int editDistanceDPComp(String s, String t) {
    int n = s.length(), m = t.length();
    int[] dp = new int[m + 1];
    // State transitions: first row
    for (int j = 1; j <= m; j++) {
        dp[j] = j;
    }
    // State transitions: remaining rows
    for (int i = 1; i <= n; i++) {
        // State transitions: first column
        int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i;
        // State transitions: remaining columns
        for (int j = 1; j <= m; j++) {
            int temp = dp[j];
            if (s.charAt(i - 1) == t.charAt(j - 1)) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = Math.min(Math.min(dp[j - 1], dp[j]), leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m];
}
edit_distance.cs
/* Edit distance: space-optimized dynamic programming */
int EditDistanceDPComp(string s, string t) {
    int n = s.Length, m = t.Length;
    int[] dp = new int[m + 1];
    // State transitions: first row
    for (int j = 1; j <= m; j++) {
        dp[j] = j;
    }
    // State transitions: remaining rows
    for (int i = 1; i <= n; i++) {
        // State transitions: first column
        int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i;
        // State transitions: remaining columns
        for (int j = 1; j <= m; j++) {
            int temp = dp[j];
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = Math.Min(Math.Min(dp[j - 1], dp[j]), leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m];
}
edit_distance.go
/* Edit distance: space-optimized dynamic programming */
func editDistanceDPComp(s string, t string) int {
    n := len(s)
    m := len(t)
    dp := make([]int, m+1)
    // State transitions: first row
    for j := 1; j <= m; j++ {
        dp[j] = j
    }
    // State transitions: remaining rows
    for i := 1; i <= n; i++ {
        // State transitions: first column
        leftUp := dp[0] // Temporarily store dp[i-1, j-1]
        dp[0] = i
        // State transitions: remaining columns
        for j := 1; j <= m; j++ {
            temp := dp[j]
            if s[i-1] == t[j-1] {
                // If the two bytes are equal, skip both (each byte is one character for ASCII input)
                dp[j] = leftUp
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = MinInt(MinInt(dp[j-1], dp[j]), leftUp) + 1
            }
            leftUp = temp // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m]
}
edit_distance.swift
/* Edit distance: space-optimized dynamic programming */
func editDistanceDPComp(s: String, t: String) -> Int {
    let n = s.utf8CString.count
    let m = t.utf8CString.count
    var dp = Array(repeating: 0, count: m + 1)
    // State transitions: first row
    for j in 1 ... m {
        dp[j] = j
    }
    // State transitions: remaining rows
    for i in 1 ... n {
        // State transitions: first column
        var leftup = dp[0] // Temporarily store dp[i-1, j-1]
        dp[0] = i
        // State transitions: remaining columns
        for j in 1 ... m {
            let temp = dp[j]
            if s.utf8CString[i - 1] == t.utf8CString[j - 1] {
                // If the two current UTF-8 bytes match, skip both
                dp[j] = leftup
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1
            }
            leftup = temp // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m]
}
edit_distance.js
/* Edit distance: space-optimized dynamic programming */
function editDistanceDPComp(s, t) {
    const n = s.length,
        m = t.length;
    const dp = new Array(m + 1).fill(0);
    // State transitions: first row
    for (let j = 1; j <= m; j++) {
        dp[j] = j;
    }
    // State transitions: remaining rows
    for (let i = 1; i <= n; i++) {
        // State transitions: first column
        let leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i;
        // State transitions: remaining columns
        for (let j = 1; j <= m; j++) {
            const temp = dp[j];
            if (s.charAt(i - 1) === t.charAt(j - 1)) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m];
}
edit_distance.ts
/* Edit distance: space-optimized dynamic programming */
function editDistanceDPComp(s: string, t: string): number {
    const n = s.length,
        m = t.length;
    const dp = new Array(m + 1).fill(0);
    // State transitions: first row
    for (let j = 1; j <= m; j++) {
        dp[j] = j;
    }
    // State transitions: remaining rows
    for (let i = 1; i <= n; i++) {
        // State transitions: first column
        let leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i;
        // State transitions: remaining columns
        for (let j = 1; j <= m; j++) {
            const temp = dp[j];
            if (s.charAt(i - 1) === t.charAt(j - 1)) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m];
}
edit_distance.dart
/* Edit distance: space-optimized dynamic programming */
int editDistanceDPComp(String s, String t) {
  int n = s.length, m = t.length;
  List<int> dp = List.filled(m + 1, 0);
  // State transitions: first row
  for (int j = 1; j <= m; j++) {
    dp[j] = j;
  }
  // State transitions: remaining rows
  for (int i = 1; i <= n; i++) {
    // State transitions: first column
    int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
    dp[0] = i;
    // State transitions: remaining columns
    for (int j = 1; j <= m; j++) {
      int temp = dp[j];
      if (s[i - 1] == t[j - 1]) {
        // If the two characters are equal, skip both of them
        dp[j] = leftup;
      } else {
        // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
        dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1;
      }
      leftup = temp; // Update to dp[i-1, j-1] for the next iteration
    }
  }
  return dp[m];
}
edit_distance.rs
/* Edit distance: space-optimized dynamic programming */
fn edit_distance_dp_comp(s: &str, t: &str) -> i32 {
    let (n, m) = (s.len(), t.len());
    let mut dp = vec![0; m + 1];
    // State transitions: first row
    for j in 1..m {
        dp[j] = j as i32;
    }
    // State transitions: remaining rows
    for i in 1..=n {
        // State transitions: first column
        let mut leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i as i32;
        // State transitions: remaining columns
        for j in 1..=m {
            let temp = dp[j];
            if s.chars().nth(i - 1) == t.chars().nth(j - 1) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = std::cmp::min(std::cmp::min(dp[j - 1], dp[j]), leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    dp[m]
}
edit_distance.c
/* Edit distance: space-optimized dynamic programming */
int editDistanceDPComp(char *s, char *t, int n, int m) {
    int *dp = calloc(m + 1, sizeof(int));
    // State transitions: first row
    for (int j = 1; j <= m; j++) {
        dp[j] = j;
    }
    // State transitions: remaining rows
    for (int i = 1; i <= n; i++) {
        // State transitions: first column
        int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
        dp[0] = i;
        // State transitions: remaining columns
        for (int j = 1; j <= m; j++) {
            int temp = dp[j];
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup;
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = myMin(myMin(dp[j - 1], dp[j]), leftup) + 1;
            }
            leftup = temp; // Update to dp[i-1, j-1] for the next iteration
        }
    }
    int res = dp[m];
    // Free memory
    free(dp);
    return res;
}
edit_distance.kt
/* Edit distance: space-optimized dynamic programming */
fun editDistanceDPComp(s: String, t: String): Int {
    val n = s.length
    val m = t.length
    val dp = IntArray(m + 1)
    // State transitions: first row
    for (j in 1..m) {
        dp[j] = j
    }
    // State transitions: remaining rows
    for (i in 1..n) {
        // State transitions: first column
        var leftup = dp[0] // Temporarily store dp[i-1, j-1]
        dp[0] = i
        // State transitions: remaining columns
        for (j in 1..m) {
            val temp = dp[j]
            if (s[i - 1] == t[j - 1]) {
                // If the two characters are equal, skip both of them
                dp[j] = leftup
            } else {
                // Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
                dp[j] = min(min(dp[j - 1], dp[j]), leftup) + 1
            }
            leftup = temp // Update to dp[i-1, j-1] for the next iteration
        }
    }
    return dp[m]
}
edit_distance.rb
### Edit distance: space-optimized dynamic programming ###
def edit_distance_dp_comp(s, t)
  n, m = s.length, t.length
  dp = Array.new(m + 1, 0)
  # State transitions: first row
  (1...(m + 1)).each { |j| dp[j] = j }
  # State transitions: remaining rows
  for i in 1...(n + 1)
    # State transitions: first column
    leftup = dp.first # Temporarily store dp[i-1, j-1]
    dp[0] += 1
    # State transitions: remaining columns
    for j in 1...(m + 1)
      temp = dp[j]
      if s[i - 1] == t[j - 1]
        # If the two characters are equal, skip both of them
        dp[j] = leftup
      else
        # Minimum edits = the minimum among the insertion, deletion, and replacement subproblems + 1
        dp[j] = [dp[j - 1], dp[j], leftup].min + 1
      end
      leftup = temp # Update to dp[i-1, j-1] for the next iteration
    end
  end
  dp[m]
end
Visualize execution

Share your insights, questions, or suggestions in the comments