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
Equalize Strings by Adding/Removing at Ends INPUT initial = "abc" a b c target = "ac" a c Allowed Operations: Add/Remove at START Add/Remove at END [+/-] a b c [+/-] Only ends can change ALGORITHM STEPS 1 Find LCS Length Longest Common Substring 2 Build DP Table Track substring matches DP Table (Substrings) a c a 1 0 b 0 0 c 0 1 Max = 1 3 Calculate Operations ops = len(init) + len(tgt) 4 Subtract 2*LCS result = 3 + 2 - 2*1 = 3 ops = m + n - 2*LCS_length FINAL RESULT Transformation Path Initial: "abc" [ a ] [ b ] [ c ] Remove 'b' (1 op) Target: "ac" [ a ] [ c ] Output: 1 Minimum Operations OK - Verified Key Insight: The Longest Common Substring (LCS) represents the maximum portion that can stay unchanged. We need to remove (m - LCS) chars from initial and add (n - LCS) chars to reach target. Total operations = (m - LCS) + (n - LCS) = m + n - 2*LCS. Here: 3 + 2 - 2*2 = 1 operation. TutorialsPoint - Equalize Strings by Adding or Removing Characters at Ends | Longest Common Substring Approach
Asked in
Google 35 Facebook 28 Amazon 22
23.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen