VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimizing-steps-to-form-anagrams-from-given-strings/

⇱ Minimizing Steps to Form Anagrams from Given Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimizing Steps to Form Anagrams from Given Strings

Last Updated : 28 Dec, 2023

Given two strings s1 and s2. You have the flexibility to add any letter to either the string s1 or s2 in just one action. Find out the least number of steps needed to transform two given words, s1, and s2, into anagrams of each other. The length of both strings can be different and it contains only lowercase English letters.

Note: The anagram strings use the same letters, but the sequence of characters can be in different order.

Examples:

Input: s1 = "geeks", s2 = "skege"
Output : 0
Explanation : Both strings s1 and s2 contains same characters.

Input: s1 = "geeksforgeeks", s2 = "geeks"
Output : 8
Explanation : In this case, we need to append "forgeeks" to s1 in 8 steps. Now "geeksforgeeks" and "geeks" are anagram of each other.

The idea is to consider all the characters that are not common to both string. We can use map and a variable to achieve this.

Follow the steps given below to implement the approach:

  • Initialize the map to maintain the character frequencies in "s1" string.
  • Iterate through the string "s1" and update the respective count of characters in the map.
  • Take a variable countofT which, is used to keep track of characters in "s2" strhasthat have no corresponding counterparts in "s1".
  • Then iterate through the "s2" string. For character found in the map, reduce their count and if the count become 0 then simply remove that character from the map else reduce the count of that character by 1.
  • Also while iterating through the "s2" string, take care of the character which is not present in map. countofT is incremented to account for the extra character present in the "s2" string.
  • After processing both strings, there may be some remaining character in the map, which represents those characters in the characters "s1" string that lacks corresponding characterin "s2" string and countofT which represents the extra character in the "s2" which is not there in "s1".
  • Now combine the count of the remaining character in the map and countofT which represents the extra character in "s2" which is not there in "s1". This combined count tells the least number of steps required to transform two given words, "s1" and "s2", into anagrams of each other.
  • Return the combined count.

Below is the implementation of the above approach.


Output
8

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: