Count of distinct permutation of a String obtained by swapping only unequal characters
Given a string find the number of unique permutations that can be obtained by swapping two indices such that the elements at these indices are distinct.
NOTE: Swapping is always performed in the original string.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: str = “sstt”
Swap str with str, string obtained “tsst” which is valid (str!=str)
Swap str with str. string obtained “tsts”
Swap str with str, string obtained “stst”
Swap str with str, string obtained “stts”
Hence total 5 strings can be obtained including the given string (“sstt”)
Input: str = “abcd”
Approach: The problem can be solved using HashMap by the following steps:
- Create a hashmap and store the frequency of every character of the given string.
- Create a variable count, to store the total number of characters in the given string, i.e. count=str.length() and a variable ans to store the number of unique permutations possible and initialize ans=0.
- Traverse the string and for each character:
- Find the number of different characters present in the right of the current index. This can be done by subtracting the frequency of that character by the total count.
- Now add this calculated value to ans, as this is the number of characters with which the current character can be swapped to create a unique permutation.
- Now, Reduce the frequency of the current character and count by 1, so that it cannot interfere with the calculations of the same elements present to the right of it.
- Return ans+1, because the given string is also a unique permutation.
Time Complexity: O(n)
Auxiliary Space: O(n)