Equalize Strings by Adding or Removing Characters at Ends - Problem
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.
Input & Output
Example 1 — Basic Transformation
$
Input:
initial = "abc", target = "ac"
›
Output:
1
💡 Note:
Remove 'b' from the middle by removing it from either end after rearranging. Actually, we can keep 'a' and 'c', so we need to remove 'b' (1 operation).
Example 2 — Complete Replacement
$
Input:
initial = "abc", target = "def"
›
Output:
6
💡 Note:
No common characters, so remove all 3 characters from initial (3 ops) and add all 3 characters for target (3 ops) = 6 operations total.
Example 3 — Partial Overlap
$
Input:
initial = "abcde", target = "cdefg"
›
Output:
4
💡 Note:
Keep common substring 'cde' (length 3). Remove 'ab' (2 ops) + add 'fg' (2 ops) = 4 operations.
Constraints
- 0 ≤ initial.length, target.length ≤ 1000
- initial and target consist of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Strings
initial and target strings
2
Find Overlap
Determine maximum characters to keep
3
Calculate Operations
Minimum operations needed
Key Takeaway
🎯 Key Insight: Find the longest common subsequence to maximize characters we can keep unchanged
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code