Minimum Steps to Convert String with Operations - Problem
You are given two strings, word1 and word2, of equal length. You need to transform word1 into word2.
For this, divide word1 into one or more contiguous substrings. For each substring substr you can perform the following operations:
- Replace: Replace the character at any one index of
substrwith another lowercase English letter. - Swap: Swap any two characters in
substr. - Reverse Substring: Reverse
substr.
Each of these counts as one operation and each character of each substring can be used in each type of operation at most once (i.e. no single index may be involved in more than one replace, one swap, or one reverse).
Return the minimum number of operations required to transform word1 into word2.
Input & Output
Example 1 — Basic Swap
$
Input:
word1 = "ab", word2 = "ba"
›
Output:
1
💡 Note:
We can transform "ab" to "ba" with a single swap operation on the entire string.
Example 2 — Multiple Operations
$
Input:
word1 = "abc", word2 = "bca"
›
Output:
2
💡 Note:
We can divide into substrings: "a" (replace to "b") costs 1, "bc" (reverse to "cb" then replace c→c, b→a) or use 2 replacements total.
Example 3 — Already Equal
$
Input:
word1 = "hello", word2 = "hello"
›
Output:
0
💡 Note:
The strings are already identical, so no operations are needed.
Constraints
- 1 ≤ word1.length, word2.length ≤ 1000
- word1.length == word2.length
- word1 and word2 consist of only lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code