PIXELBANKv9.1.0
Menu

Compute the Levenshtein edit distance between two strings.

The edit distance is the minimum number of single-character operations to transform one string into another:

  • Insert a character
  • Delete a character
  • Replace a character

Use dynamic programming with a matrix of size (m+1) x (n+1).

Recurrence: dp[i][j]={jif i=0iif j=0dp[i−1][j−1]if s1[i−1]=s2[j−1]1+min⁡(dp[i−1][j],dp[i][j−1],dp[i−1][j−1])otherwisedp[i][j] = \begin{cases} j & \text{if } i = 0 \\ i & \text{if } j = 0 \\ dp[i-1][j-1] & \text{if } s1[i-1] = s2[j-1] \\ 1 + \min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) & \text{otherwise} \end{cases}

Input format:

  • Line 1: First string
  • Line 2: Second string

Output: The edit distance (integer).

Example:

Input:
kitten
sitting
Output:
3
Reasoning:

Transforming "kitten" to "sitting":

  1. kitten -> sitten (replace k with s)
  2. sitten -> sittin (replace e with i)
  3. sittin -> sitting (insert g at end)

Minimum 3 operations needed.

Constraints:

  • Strings can contain any characters
  • All operations cost 1
  • Empty strings are valid inputs
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Edit Distance - Medium | PixelBank