Count anagrams having first character as a consonant and no pair of consonants or vowels placed adjacently | C ++ program for the above approach ; Function to compute factorials till N ; Iterate in the range [ 1 , N ] ; Update ans to ans * i ; Store the value of ans in fac [ i ] ; Function to check whether the current character is a vowel or not ; Function to count the number of anagrams of S satisfying the given condition ; Store the factorials upto N ; Function Call to generate all factorials upto n ; Create a hashmap to store frequencies of all characters ; Store the count of vowels and consonants ; Iterate through all characters in the string ; Update the frequency of current character ; Check if the character is vowel or consonant ; Check if C == V + 1 or C == V ; Store the denominator ; Calculate the denominator of the expression ; Multiply denominator by factorial of counts of all letters ; Store the numerator ; Store the answer by dividing numerator by denominator ; Print the answer ; Otherwise , print 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll  long long NEW_LINE #define mod  1000000007 NEW_LINE #define N  1000001 NEW_LINE using namespace std ; void Precomputefact ( unordered_map < ll , ll > & fac ) { ll ans = 1 ; for ( ll i = 1 ; i <= N ; i ++ ) { ans = ( ans * i ) % mod ; fac [ i ] = ans ; } return ; } bool isVowel ( char a ) { if ( a == ' A ' a == ' E ' a == ' I ' a == ' O ' a == ' U ' ) return true ; else return false ; } void countAnagrams ( string s , int n ) { unordered_map < ll , ll > fac ; Precomputefact ( fac ) ; unordered_map < char , ll > count ; int vo = 0 , co = 0 ; for ( int i = 0 ; i < n ; i ++ ) { count [ s [ i ] ] ++ ; if ( isVowel ( s [ i ] ) ) vo ++ ; else co ++ ; } if ( ( co == vo + 1 ) || ( co == vo ) ) { ll deno = 1 ; for ( auto c : count ) { deno = ( deno * fac [ c . second ] ) % mod ; } ll nume = fac [ co ] % mod ; nume = ( nume * fac [ vo ] ) % mod ; ll ans = nume / deno ; cout << ans ; } else { cout << 0 ; } } int main ( ) { string S = " GADO " ; int l = S . size ( ) ; countAnagrams ( S , l ) ; return 0 ; }