
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number of Permutations of a Given String in C++
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