Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Count of distinct permutation of a String obtained by swapping only unequal characters

  • Difficulty Level : Medium
  • Last Updated : 10 Aug, 2021

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.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Examples:



Input: str = “sstt”
Output: 5
Explaination: 
Swap str[0] with str[2], string obtained “tsst” which is valid (str[0]!=str[2])
Swap str[0] with str[3]. string obtained “tsts”
Swap str[1] with str[2], string obtained “stst”
Swap str[1] with str[3], string obtained “stts”
Hence total 5 strings can be obtained including the given string (“sstt”)

Input: str = “abcd”
Output: 7

Approach: The problem can be solved using HashMap by the following steps:

  1. Create a hashmap and store the frequency of every character of the given string.
  2. 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.
  3. 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.
  4. Return ans+1, because the given string is also a unique permutation.

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate total
// number of valid permutations
int validPermutations(string str)
{
    unordered_map<char, int> m;
 
    // Creating count which is equal to the
    // Total number of characters present and
    // ans that will store the number of unique
    // permutations
    int count = str.length(), ans = 0;
 
    // Storing frequency of each character
    // present in the string
    for (int i = 0; i < str.length(); i++) {
        m[str[i]]++;
    }
    for (int i = 0; i < str.length(); i++) {
        // Adding count of characters by excluding
        // characters equal to current char
        ans += count - m[str[i]];
 
        // 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.
        m[str[i]]--;
        count--;
    }
 
    // Return ans+1 (Because the given string
    // is also a unique permutation)
    return ans + 1;
}
 
// Driver Code
int main()
{
    string str = "sstt";
    cout << validPermutations(str);
    return 0;
}

Java




// Java program for the above approach
 
// Importing HashMap class
import java.util.HashMap;
 
class GFG {
 
    // Function to calculate total
    // number of valid permutations
    static int validPermutations(String str)
    {
 
        HashMap<Character, Integer> m
            = new HashMap<Character, Integer>();
 
        // Creating count which is equal to the
        // Total number of characters present and
        // ans that will store the number of unique
        // permutations
        int count = str.length(), ans = 0;
 
        // Storing frequency of each character
        // present in the string
        for (int i = 0; i < str.length(); i++) {
            m.put(str.charAt(i),
                  m.getOrDefault(str.charAt(i), 0) + 1);
        }
 
        for (int i = 0; i < str.length(); i++) {
            // Adding count of characters by excluding
            // characters equal to current char
            ans += count - m.get(str.charAt(i));
 
            // 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.
            m.put(str.charAt(i), m.get(str.charAt(i)) - 1);
            count--;
        }
 
        // Return ans+1 (Because the given string
        // is also a unique permutation)
        return ans + 1;
    }
 
    public static void main(String[] args)
    {
        String str = "sstt";
 
        System.out.println(validPermutations(str));
    }
}
 
// This code is contributed by rajsanghavi9.

Python3




# Python 3 program for the above approach
 
# Function to calculate total
# number of valid permutations
def validPermutations(str):
    m = {}
 
    # Creating count which is equal to the
    # Total number of characters present and
    # ans that will store the number of unique
    # permutations
    count = len(str)
    ans = 0
 
    # Storing frequency of each character
    # present in the string
    for i in range(len(str)):
        if(str[i] in m):
            m[str[i]] += 1
        else:
            m[str[i]] = 1
    for i in range(len(str)):
       
        # Adding count of characters by excluding
        # characters equal to current char
        ans += count - m[str[i]]
 
        # 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.
        m[str[i]] -= 1
        count -= 1
 
    # Return ans+1 (Because the given string
    # is also a unique permutation)
    return ans + 1
 
# Driver Code
if __name__ == '__main__':
    str = "sstt"
    print(validPermutations(str))
 
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# program for the above approach
 
// Importing Dictionary class
using System;
using System.Collections.Generic;
 
 
public class GFG {
 
    // Function to calculate total
    // number of valid permutations
    static int validPermutations(String str)
    {
 
        Dictionary<char, int> m
            = new Dictionary<char, int>();
 
        // Creating count which is equal to the
        // Total number of characters present and
        // ans that will store the number of unique
        // permutations
        int count = str.Length, ans = 0;
 
        // Storing frequency of each character
        // present in the string
        for (int i = 0; i < str.Length; i++) {
            if(m.ContainsKey(str[i]))
                m[str[i]]=m[str[i]]+1;
            else
                m.Add(str[i], 1);
        }
 
        for (int i = 0; i < str.Length; i++) {
            // Adding count of characters by excluding
            // characters equal to current char
            ans += count - m[str[i]];
 
            // 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.
            if(m.ContainsKey(str[i]))
                m[str[i]]=m[str[i]]-1;
            count--;
        }
 
        // Return ans+1 (Because the given string
        // is also a unique permutation)
        return ans + 1;
    }
 
    public static void Main(String[] args)
    {
        String str = "sstt";
 
        Console.WriteLine(validPermutations(str));
    }
}
 
// This code is contributed by shikhasingrajput

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to calculate total
// number of valid permutations
function validPermutations(str) {
  let m = new Map();
 
  // Creating count which is equal to the
  // Total number of characters present and
  // ans that will store the number of unique
  // permutations
  let count = str.length,
    ans = 0;
 
  // Storing frequency of each character
  // present in the string
  for (let i = 0; i < str.length; i++) {
    if (m.has(str[i])) {
      m.set(str[i], m.get(str[i]) + 1);
    } else {
      m.set(str[i], 1);
    }
  }
  for (let i = 0; i < str.length; i++)
  {
   
    // Adding count of characters by excluding
    // characters equal to current char
    ans += count - m.get(str[i]);
 
 
    // 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.
    m.set(str[i], m.get(str[i]) - 1);
    count--;
  }
 
  // Return ans+1 (Because the given string
  // is also a unique permutation)
  return ans + 1;
}
 
// Driver Code
let str = "sstt";
document.write(validPermutations(str));
 
</script>

 
 

Output: 
5

 

 Time Complexity: O(n)

Auxiliary Space: O(n)




My Personal Notes arrow_drop_up
Recommended Articles
Page :