C++ Program to Find the Number of Permutations of a Given String

C++Server Side ProgrammingProgramming

We can arrange the characters of a string in different order. Here we will see how we can count the number of permutations can be formed from a given string.

We know that if one string is ‘abc’. It has three characters; we can arrange them into 3! = 6 different ways. So a string with n characters, we can arrange them into n! different ways. But now if there are same characters are present for multiple times, like aab, then there will not be 6 permutations.

• aba
• aab
• baa
• baa
• aab
• aba

Here the (1,6), (2, 5), (3,4) are same. So here the number of permutations is 3. This is basically (n!)/(sum of the factorials of all characters which is occurring more than one times).

To solve this problem, at first we have to calculate the frequency of all of the characters. Then count the factorial of n, then divide it by doing sum of all frequency values which are greater than 1.

Example Code

#include<iostream>
using namespace std;
long fact(long n) {
if(n == 0 || n == 1 )
return 1;
return n*fact(n-1);
}
int countPermutation(string str) {
int freq[26] = {0};
for(int i = 0; i<str.size(); i++) {
freq[str[i] - 'a']++; //get the frequency of each characters individually
}
int res = fact(str.size()); //n! for string of length n
for(int i = 0; i<26; i++) {
if(freq[i] > 1)
res /= fact(freq[i]); //divide n! by (number of occurrences of each characters)!
}
return res;
}
main(){
string n;
cout << "Enter a number to count number of permutations can be possible: ";
cin >> n;
cout << "\nThe number of permutations: " << countPermutation(n);
}

Output

Enter a number to count number of permutations can be possible: abbc
The number of permutations: 12
Published on 28-May-2019 11:55:29