Lexicographically Kth | Python3 program for the above approach ; Function to fill dp array ; Initialize all the entries with 0 ; Update dp [ 0 ] [ 0 ] to 1 ; Traverse the dp array ; Update the value of dp [ i ] [ j ] ; Recursive function to find the Kth lexicographical smallest string ; Handle the base cases ; If there are more than or equal to K strings which start with a , then the first character is 'a ; Otherwise the first character of the resultant string is 'b ; Function to find the Kth lexicographical smallest string ; Function call to fill the dp array ; Print the resultant ; Given Input ; Function Call
from typing import Mapping NEW_LINE MAX = 30 NEW_LINE def findNumString ( X , Y , dp ) : NEW_LINE INDENT for i in range ( 0 , MAX ) : NEW_LINE INDENT for j in range ( 0 , MAX ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 0 , X + 1 ) : NEW_LINE INDENT for j in range ( 0 , Y + 1 ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def kthString ( X , Y , K , dp ) : NEW_LINE INDENT x1 = " " NEW_LINE y1 = " " NEW_LINE for i in range ( 0 , Y ) : NEW_LINE INDENT x1 += ' b ' NEW_LINE DEDENT for i in range ( 0 , X ) : NEW_LINE INDENT y1 += ' a ' NEW_LINE DEDENT if ( X == 0 ) : NEW_LINE INDENT return x1 NEW_LINE DEDENT if ( Y == 0 ) : NEW_LINE INDENT return y1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( K <= dp [ X - 1 ] [ Y ] ) : NEW_LINE INDENT return " a " + kthString ( X - 1 , Y , K , dp ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT return " b " + kthString ( X , Y - 1 , K - dp [ X - 1 ] [ Y ] , dp ) NEW_LINE DEDENT DEDENT def kthStringUtil ( X , Y , K ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( MAX ) ] for col in range ( MAX ) ] NEW_LINE findNumString ( X , Y , dp ) NEW_LINE print ( kthString ( X , Y , K , dp ) ) NEW_LINE DEDENT X = 4 NEW_LINE Y = 3 NEW_LINE K = 4 NEW_LINE kthStringUtil ( X , Y , K ) NEW_LINE