VOOZH about

URL: https://www.geeksforgeeks.org/dsa/transform-one-string-to-another-using-minimum-number-of-given-operation/

⇱ Transform String to Another using Minimum Operations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Transform String to Another using Minimum Operations

Last Updated : 30 Apr, 2026

Given two strings s1 and s2. Find the minimum number of steps required to transform string s1 into string s2. The only allowed operation for the transformation is selecting a character from string s1 and inserting it in the beginning of string s2.

Examples:

Input: s1 = "abd", s2 = "bad"
Output: 1
Explanation: The conversion can take place in 1 operation: Pick 'b' and place it at the front.

Input: s1 = "GeeksForGeeks" s2 = "ForGeeksGeeks"
Output: 3
Explanation: The conversion can take place in 3 operations:
Pick 'r' and place it at the front, A = "rGeeksFoGeeks"
Pick 'o' and place it at the front, A = "orGeeksFGeeks"
Pick 'F' and place it at the front, A = "ForGeeksGeeks"

Using Hash Map (or Dictionary) and Two Pointers - O(n) Time

The transformation is only possible if both strings have the same characters with the exact same frequencies. use a HashMap (or a frequency array) to count the characters in string s1 and then "cancel them out" using string s2.

If frequencies are same, then begin matching from end of both strings.

  • Keep moving both pointers while there is a match
  • For mismatches, increment result and move only pointer of s1 as the current substring of s1 can match with current prefix of s2.

Output
3

Note : We can further optimize the above approach by using a count array of size 256 instead of map.

Comment
Article Tags:
Article Tags: