Number of distinct permutation a String can have | Java program to find number of distinct permutations of a string . ; Utility function to find factorial of n . ; Returns count of distinct permutations of str . ; finding frequency of all the lower case alphabet and storing them in array of integer ; finding factorial of number of appearances and multiplying them since they are repeating alphabets ; finding factorial of size of string and dividing it by factorial found after multiplying ; Driver code
public class GFG { static final int MAX_CHAR = 26 ; static int factorial ( int n ) { int fact = 1 ; for ( int i = 2 ; i <= n ; i ++ ) fact = fact * i ; return fact ; } static int countDistinctPermutations ( String str ) { int length = str . length ( ) ; int [ ] freq = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < length ; i ++ ) if ( str . charAt ( i ) >= ' a ' ) freq [ str . charAt ( i ) - ' a ' ] ++ ; int fact = 1 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) fact = fact * factorial ( freq [ i ] ) ; return factorial ( length ) / fact ; } public static void main ( String args [ ] ) { String str = " fvvfhvgv " ; System . out . println ( countDistinctPermutations ( str ) ) ; } }