554. Equalize Strings by Adding or Removing Characters at Ends

Given two strings, initial and target. The task is to modify initial by performing a series of operations to make it equal to target.

In one operation:

  • Add one character only at the beginning or the end of initial.
  • Remove one character only from the beginning or the end of initial.

Return the minimum number of operations required to transform initial into target.

Example 1:

Input: initial = "abcdef", target = "defgh"

Output: 5

Explanation:

Remove 'a', 'b', 'c' from the beginning → "def"

Add 'g' and 'h' to the end → "defgh"

Example 2:

Input: initial = "pqrrt", target = "rtsp"

Output: 5

Explanation:

Remove from beginning -> "qrrt"

Remove from beginning -> "rrt"

Remove from beginning -> "rt"

Add 's' to end -> "rts"

Add 'p' to end -> "rtsp"

Now Your Turn!

Pick the correct output for the given input

Input: initial = "mnop", target = "mnopqr"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= initial.length, target.length <= 1000
  • initial and target consist only of lowercase English letters.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int minOperations(string initial, string target) {
}
};
Test Case

Input:

Initial
Target