![]() |
VOOZH | about |
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"
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.
3
Note : We can further optimize the above approach by using a count array of size 256 instead of map.