K length words that can be formed from given characters without repetition | Java 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 java . util . * ; class solution { static int findPermutation ( String str , int k ) { boolean [ ] has = new boolean [ 26 ] ; Arrays . fill ( has , false ) ; int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! has [ str . charAt ( i ) - ' a ' ] ) { cnt ++ ; has [ str . charAt ( i ) - ' a ' ] = true ; } } int ans = 1 ; for ( int i = 2 ; i <= cnt ; i ++ ) ans *= i ; for ( int i = cnt - k ; i > 1 ; i -- ) ans /= i ; return ans ; } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; int k = 4 ; System . out . println ( findPermutation ( str , k ) ) ; } }