Find the lexicographically smallest string which satisfies the given condition | Function to return the required string ; First character will always be 'a ; To store the resultant string ; Since length of the string should be greater than 0 and first element of array should be 1 ; Check one by one all element of given prefix array ; If the difference between any two consecutive elements of the prefix array is greater than 1 then there will be no such string possible that satisfies the given array . Also , string cannot have more than 26 distinct characters ; If difference is 0 then the ( i + 1 ) th character will be same as the ith character ; If difference is 1 then the ( i + 1 ) th character will be different from the ith character ; Return the resultant string ; Driver code
def smallestString ( N , A ) : NEW_LINE ' NEW_LINE INDENT ch = ' a ' NEW_LINE S = " " NEW_LINE if ( N < 1 or A [ 0 ] != 1 ) : NEW_LINE INDENT S = " - 1" NEW_LINE return S NEW_LINE DEDENT S += str ( ch ) NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT diff = A [ i ] - A [ i - 1 ] NEW_LINE if ( diff > 1 or diff < 0 or A [ i ] > 26 ) : NEW_LINE INDENT S = " - 1" NEW_LINE return S NEW_LINE DEDENT elif ( diff == 0 ) : NEW_LINE INDENT S += ' a ' NEW_LINE DEDENT else : NEW_LINE INDENT S += ch NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE DEDENT DEDENT return S NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( smallestString ( n , arr ) ) NEW_LINE