K length words that can be formed from given characters without repetition | Python3 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
import math as mt NEW_LINE def findPermutation ( string , k ) : NEW_LINE INDENT has = [ False for i in range ( 26 ) ] NEW_LINE cnt = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( has [ ord ( string [ i ] ) - ord ( ' a ' ) ] == False ) : NEW_LINE INDENT cnt += 1 NEW_LINE has [ ord ( string [ i ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE for i in range ( 2 , cnt + 1 ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT for i in range ( cnt - k , 1 , - 1 ) : NEW_LINE INDENT ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT string = " geeksforgeeks " NEW_LINE k = 4 NEW_LINE print ( findPermutation ( string , k ) ) NEW_LINE