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 substr with 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
Minimum Steps to Convert String INPUT word1 a b [0] [1] word2 b a [0] [1] Input Values: word1 = "ab" word2 = "ba" length = 2 ALGORITHM STEPS 1 Compare Strings Check if word1 != word2 2 Identify Pattern "ab" vs "ba" = swap needed 3 Choose Operation SWAP or REVERSE works 4 Execute Greedy Min ops = 1 operation Swap Operation a b b a swap Operations used: 1 FINAL RESULT Transformed String b a = word2 [OK] Output 1 Verification - One SWAP operation used - word1 now equals word2 - Minimum achieved [OK] Key Insight: The Greedy approach identifies that when two adjacent characters need to be swapped, a single SWAP or REVERSE operation is optimal. For "ab" --> "ba", swapping positions [0] and [1] transforms the entire string in just ONE operation, which is the minimum possible for this transformation. TutorialsPoint - Minimum Steps to Convert String with Operations | Greedy Optimization
Asked in
Google 25 Microsoft 20 Amazon 15
12.3K Views
Medium Frequency
~35 min Avg. Time
487 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