- Related Questions & Answers
- C Program to print all permutations of a given string
- Python Program to print all permutations of a given string
- Print all permutations of a given string
- How to find all possible permutations of a given string in Python?
- C++ program to concatenate a string given number of times?
- Golang Program to find the parity of a given number.
- C++ Program to Find the Number of occurrences of a given Number using Binary Search approach
- Java Program to print distinct permutations of a string
- Print all distinct permutations of a given string with duplicates in C++
- Java program to find the square root of a given number
- Java program to find the cube root of a given number
- C# Program to find number of occurrence of a character in a String
- Java program to find a cube of a given number
- Print k different sorted permutations of a given array in C Program.
- Print all the palindromic permutations of given string in alphabetic order in C++

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

#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); }

Enter a number to count number of permutations can be possible: abbc The number of permutations: 12

Advertisements