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
< ? php function findPermutation ( $ str , $ k ) { $ has = array ( ) ; for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { $ has [ $ i ] = false ; } $ cnt = 0 ; for ( $ i = 0 ; $ i < strlen ( $ str ) ; $ i ++ ) { if ( $ has [ ord ( $ str [ $ i ] ) - ord ( ' a ' ) ] == false ) { $ cnt ++ ; $ has [ ord ( $ str [ $ i ] ) - ord ( ' a ' ) ] = true ; } } $ ans = 1 ; for ( $ i = 2 ; $ i <= $ cnt ; $ i ++ ) $ ans *= $ i ; for ( $ i = $ cnt - $ k ; $ i > 1 ; $ i -- ) $ ans /= $ i ; return $ ans ; } $ str = " geeksforgeeks " ; $ k = 4 ; echo findPermutation ( $ str , $ k ) ; ? >