Find Kth lexicographical ordered numeric string of length N with distinct products of each substring | Java 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
s = ' ' NEW_LINE K = 0 NEW_LINE def getString ( curlen , N , prod ) : NEW_LINE INDENT global s , K NEW_LINE if ( curlen == N ) : NEW_LINE INDENT K -= 1 NEW_LINE if ( K == 0 ) : NEW_LINE INDENT ans = s NEW_LINE DEDENT return NEW_LINE DEDENT ch = '2' NEW_LINE while ( ch <= '9' ) : NEW_LINE INDENT s = chr ( ord ( s ) + ord ( ch ) ) NEW_LINE ok = 1 NEW_LINE t = 1 NEW_LINE i = curlen NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE while ( i >= 0 and len ( s ) ) : NEW_LINE INDENT t *= ord ( s [ i ] ) - 48 NEW_LINE if ( prod [ t ] != 0 ) : NEW_LINE INDENT ok = 0 NEW_LINE DEDENT prod [ t ] += 1 NEW_LINE i -= 1 NEW_LINE DEDENT if ( ok != 0 ) : NEW_LINE INDENT getString ( curlen + 1 , N , prod ) NEW_LINE DEDENT t = 1 NEW_LINE i = curlen NEW_LINE while ( i >= 0 and len ( s ) > i ) : NEW_LINE INDENT i -= 1 NEW_LINE t *= ord ( s [ i ] ) - 48 NEW_LINE prod [ t ] -= 1 NEW_LINE DEDENT if ( len ( s ) > 0 ) : NEW_LINE INDENT s = s [ 0 : len ( s ) - 1 ] NEW_LINE DEDENT DEDENT DEDENT def kthValidString ( N ) : NEW_LINE INDENT if ( N > 10 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT if ( K > 10 ) : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT s = " " NEW_LINE K -= 1 NEW_LINE s += ( K + '0' ) NEW_LINE return s NEW_LINE DEDENT ans = " - 1" NEW_LINE s = " " NEW_LINE prod = [ 0 ] * 10005 NEW_LINE getString ( 0 , N , prod ) NEW_LINE return ans NEW_LINE DEDENT N = 3 NEW_LINE K = 4 NEW_LINE print ( kthValidString ( N ) ) NEW_LINE