![]() |
Given two strings X and Y, we need to convert string X into an anagram of string Y with minimum replacements. If we have multiple ways of achieving the target, we go for the lexicographically smaller string where the length of each string Examples: Input : X = "CDBABC" Y = "ADCABD" Output : Anagram : ADBADC Number of changes made: 2 Input : X = "PJPOJOVMAK" Y = "FVACRHLDAP" Output : Anagram : ACPDFHVLAR Number of changes made: 7 Approach used: We have to convert string X into a lexicographically smallest anagram of string Y doing minimum replacements in the original string X. We maintain two counter arrays that store the count/frequency of each character in the two strings. Let counters of the two strings be Half the job is done as we know how many replacements are to be done. We now need the lexicographically smaller string. Now, for a specific position, we look for all possible characters from ‘A’ to ‘Z’ and check for each character whether it could be fit in this position or now. For a better understanding, we iterate for each position in the string. Check if is there is a character that is there in string Y and not in string X (or the frequency of character is more in string Y and less in string X). Now, if there is one, we check that the character at the current position in X, is it unnecessary? i.e. does it have more frequency in string X and less frequency in string Y. Now, if all the boxes are ticked, we further check if we insert the character in this position, as we need to generate the lexicographically smaller string. If all the conditions are true, we replace the character in string X with the character in string Y. After all such replacements, we can print the altered string X as the output. Implementation: C++
Java
Python3
C#
Javascript
Output Anagram : ADBADC Number of changes made : 2 Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the length of the string. |
Reffered: https://www.geeksforgeeks.org
Strings |
Related |
---|
![]() |
|
|
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |