K length words that can be formed from given characters without repetition | C ++ implementation of the approach ; Function to return the required count ; To store the count of distinct characters in str ; Traverse str character by character ; If current character is appearing for the first time in str ; Increment the distinct character count ; Update the appearance of the current character ; Since P ( n , r ) = n ! / ( n - r ) ! ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findPermutation ( string str , int k ) { bool has [ 26 ] = { false } ; int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! has [ str [ i ] - ' a ' ] ) { cnt ++ ; has [ str [ i ] - ' a ' ] = true ; } } long long int ans = 1 ; for ( int i = 2 ; i <= cnt ; i ++ ) ans *= i ; for ( int i = cnt - k ; i > 1 ; i -- ) ans /= i ; return ans ; } int main ( ) { string str = " geeksforgeeks " ; int k = 4 ; cout << findPermutation ( str , k ) ; return 0 ; }