Equalize Strings by Adding or Removing Characters at Ends Problem
Description
LeetCode Problem 3135.
Given two strings initial and target, your task is to modify initial by performing a series of operations to make it equal to target.
In one operation, you can add or remove one character only at the beginning or the end of the string initial.
Return the minimum number of operations required to transform initial into target.
Example 1:
Input: initial = "abcde", target = "cdef"
Output: 3
Explanation:
Remove 'a' and 'b' from the beginning of initial, then add 'f' to the end.
Example 2:
Input: initial = "axxy", target = "yabx"
Output: 6
Explanation:
Operation Resulting String
Add 'y' to the beginning "yaxxy"
Remove from end "yaxx"
Remove from end "yax"
Remove from end "ya"
Add 'b' to the end "yab"
Add 'x' to the end "yabx"
Example 3:
Input: initial = "xyz", target = "xyz"
Output: 0
Explanation:
No operations are needed as the strings are already equal.
Constraints:
1 <= initial.length, target.length <= 1000initialandtargetconsist only of lowercase English letters.
Solution
Approach: Longest Common Substring (DP)
We can only delete or add characters at the ends, so whatever stays of initial is a contiguous block that must also appear in target. Keeping a longest common substring of length mx is best: delete m - mx characters from initial and add n - mx characters to reach target, for m + n - 2 * mx operations in total (m, n are the lengths).
To find mx, let f[i][j] be the length of the longest common substring ending at initial[i - 1] and target[j - 1]. If the two characters are equal, f[i][j] = f[i - 1][j - 1] + 1, otherwise 0. mx is the largest value of f.
Complexity: time O(m * n), space O(m * n).
class Solution:
def minOperations(self, initial: str, target: str) -> int:
m, n = len(initial), len(target)
f = [[0] * (n + 1) for _ in range(m + 1)]
mx = 0
for i, a in enumerate(initial, 1):
for j, b in enumerate(target, 1):
if a == b:
f[i][j] = f[i - 1][j - 1] + 1
mx = max(mx, f[i][j])
return m + n - mx * 2