Find Kth lexicographical ordered numeric string of length N with distinct products of each substring | JavaScript program for the above approach ; Function to find the required String ; If the current length is equal to n exit from here only ; Iterate for all the characters ; Check if the product is present before ; If the current String is good then recurse for the next character ; Decrease all the products back to their original state ; Erase the last character ; Function to calculate kth ordered valid String ; Check for the base cases ; There are atmost 10 valid Strings for n = 1 ; Vector to keep a check on number of occurences of products ; Recursively construct the Strings ; Driver Code
var ans , s ; var K ; function getString ( curlen , N , prod ) { if ( curlen == N ) { K -- ; if ( K == 0 ) ans = s ; return ; } var ch ; var ok , t , i ; for ( ch = ' ' ; ch <= ' ' ; ch ++ ) { s += ch ; ok = 1 ; t = 1 ; for ( i = curlen ; i >= 0 && s . length > i ; i -- ) { t *= s . charAt ( i ) - 48 ; if ( prod [ t ] != 0 ) ok = 0 ; prod [ t ] ++ ; } if ( ok != 0 ) getString ( curlen + 1 , N , prod ) ; t = 1 ; for ( i = curlen ; i >= 0 && s . length > i ; i -- ) { t *= s . charAt ( i ) - 48 ; prod [ t ] -- ; } if ( s . length > 0 ) s = s . substring ( 0 , s . length - 1 ) ; } } function kthValidString ( N ) { if ( N > 10 ) { return " " ; } if ( N == 1 ) { if ( K > 10 ) { return " " ; } var s = " " ; K -- ; s += ( K + ' ' ) ; return s ; } var ans = " " ; var s = " " ; var prod = new Array ( 10005 ) ; getString ( 0 , N , prod ) ; return ans ; } var N = 3 ; var K = 4 ; document . write ( kthValidString ( N ) ) ;