Equalize Strings by Adding or Removing Characters at Ends - Problem
Imagine you have a magical word transformer that can only work at the beginning and end of strings! Given two strings initial and target, your mission is to transform the initial string into the target string using the minimum number of operations.
In each operation, you can:
- Add one character at the beginning or end of
initial - Remove one character from the beginning or end of
initial
Goal: Find the minimum number of operations needed to make initial equal to target.
Example: If initial = "abc" and target = "def", you could remove all 3 characters from initial and add 3 new ones, requiring 6 operations total.
Input & Output
example_1.py โ Basic Transformation
$
Input:
initial = "abc", target = "def"
โบ
Output:
6
๐ก Note:
No common substring exists between "abc" and "def". We need to remove all 3 characters from initial (3 operations) and add all 3 characters of target (3 operations), totaling 6 operations.
example_2.py โ Partial Overlap
$
Input:
initial = "programming", target = "algorithm"
โบ
Output:
14
๐ก Note:
The longest common substring is "gra" (length 3). We remove 11-3=8 characters from initial and add 9-3=6 characters to reach target. Total: 8+6=14 operations.
example_3.py โ Identical Strings
$
Input:
initial = "hello", target = "hello"
โบ
Output:
0
๐ก Note:
The strings are already identical, so no operations are needed. The entire string is the common substring.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Common Pattern
Find the longest pattern that exists in both ribbons
2
Plan Cuts
Decide which parts to cut from the ends of the first ribbon
3
Plan Additions
Decide what new pieces to attach to the ends
4
Calculate Total Work
Sum up all the cutting and attaching operations needed
Key Takeaway
๐ฏ Key Insight: The minimum operations equal the total length of both strings minus twice the length of their longest common substring, because we preserve the common part and replace everything else.
Time & Space Complexity
Time Complexity
O(n ร m)
O(n) substrings of initial ร O(m) to check each in target string
โ Linear Growth
Space Complexity
O(m)
Space for storing target string and hash lookups
โ Linear Space
Constraints
- 0 โค initial.length, target.length โค 1000
- initial and target consist of only lowercase English letters
- Time limit: 2 seconds per test case
- Memory limit: 256 MB
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code