K length words that can be formed from given characters without repetition | 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
function findPermutation ( str , k ) { var has = new Array ( 26 ) ; for ( var i = 0 ; i < 26 ; i ++ ) has [ i ] = false ; var cnt = 0 ; for ( var i = 0 ; i < str . length ; i ++ ) { if ( ! has [ str [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] ) { cnt ++ ; has [ str [ i ] . charCodeAt ( 0 ) - " " . charCodeAt ( 0 ) ] = true ; } } var ans = 1 ; for ( var i = 2 ; i <= cnt ; i ++ ) ans *= i ; for ( var i = cnt - k ; i > 1 ; i -- ) ans /= i ; return ans ; } var str = " " ; var k = 4 ; document . write ( findPermutation ( str , k ) ) ;