KatInterview

Minimum Edit Distance Between Two Palindromes

StringsAuto-graded · 19 test cases
MediumAuto-gradedStringsstringsdynamic programmingedit distance

Last updated

Tests understanding of edit distance (insert, delete, substitute) by computing the minimum operations needed to transform one palindrome into another, reinforcing dynamic programming on strings.

Minimum Edit Distance Between Two Palindromes

You are given two strings, s and t, each of which is guaranteed to be a palindrome.

Your task is to compute the minimum edit distance (also known as Levenshtein distance) required to transform s into t, using only the following three operations, each with a cost of 1:

  • Insert a single character anywhere in the string.
  • Delete a single character from the string.
  • Substitute one character for another at any position.

Because both strings are palindromes, intermediate states during the transformation do not need to be palindromes — only the start (s) and the end result (which must equal t) matter.

Return the minimum total cost to transform s into t.

Constraints

  • 1 ≤ len(s), len(t) ≤ 1000
  • Both s and t consist only of lowercase English letters (a–z).
  • Both s and t are valid palindromes (you may assume this without validation).
  • The answer fits in a standard 32-bit integer.

Examples

Example 1

Input: min_palindrome_edit_distance('racecar', 'racecar')

Output: 0

Example 2

Input: min_palindrome_edit_distance('aba', 'aabaa')

Output: 2

Example 3

Input: min_palindrome_edit_distance('abacaba', 'aca')

Output: 4

Hints

Hint 1

Think about how the classic Levenshtein (edit distance) DP works on two arbitrary strings — the palindrome property doesn't change the algorithm, but it affects which interesting test cases arise (e.g., odd vs. even length palindromes, single-character strings).

Hint 2

Set up a 2D DP table where dp[i][j] = minimum edits to convert s[:i] into t[:j]. Fill it row by row: if characters match, carry the diagonal; otherwise take 1 + min(diagonal, left, above).

Hint 3

The palindrome constraint means certain patterns recur (repeated characters, mirror structure), so watch out for cases where a substitution saves two insertions/deletions or vice versa — the DP handles all of this automatically.