Smallest number greater than Y with sum of digits equal to X | Function to return the minimum string of length d having the sum of digits s ; Return a string of length d ; Greedily put 9 's  in the end ; Put remaining sum ; Function to find the smallest number greater than Y whose sum of digits is X ; Convert number y to string ; Maintain prefix sum of digits ; Iterate over Y from the back where k is current length of suffix ; Stores current digit ; Increase current digit ; Sum upto current prefix ; Return answer if remaining sum can be obtained in suffix ; Find suffix of length k having sum of digits x - r ; Append current character ; Return the result ; Driver Code ; Given Number and Sum ; Function Call
def helper ( d , s ) : NEW_LINE INDENT ans = [ '0' ] * d NEW_LINE for i in range ( d - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s >= 9 ) : NEW_LINE INDENT ans [ i ] = '9' NEW_LINE s -= 9 NEW_LINE DEDENT else : NEW_LINE INDENT c = chr ( s + ord ( '0' ) ) NEW_LINE ans [ i ] = c ; NEW_LINE s = 0 ; NEW_LINE DEDENT DEDENT return ' ' . join ( ans ) ; NEW_LINE DEDENT def findMin ( x , Y ) : NEW_LINE INDENT y = str ( Y ) ; NEW_LINE n = len ( y ) NEW_LINE p = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT p [ i ] = ( ord ( y [ i ] ) - ord ( '0' ) ) NEW_LINE if ( i > 0 ) : NEW_LINE INDENT p [ i ] += p [ i - 1 ] ; NEW_LINE DEDENT DEDENT n - 1 NEW_LINE k = 0 NEW_LINE while True : NEW_LINE INDENT d = 0 ; NEW_LINE if ( i >= 0 ) : NEW_LINE INDENT d = ( ord ( y [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT for j in range ( d + 1 , 10 ) : NEW_LINE INDENT r = ( ( i > 0 ) * p [ i - 1 ] + j ) ; NEW_LINE if ( x - r >= 0 and x - r <= 9 * k ) : NEW_LINE INDENT suf = helper ( k , x - r ) ; NEW_LINE pre = " " ; NEW_LINE if ( i > 0 ) : NEW_LINE INDENT pre = y [ 0 : i ] NEW_LINE DEDENT cur = chr ( j + ord ( '0' ) ) NEW_LINE pre += cur ; NEW_LINE return pre + suf ; NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 18 ; NEW_LINE y = 99 ; NEW_LINE print ( findMin ( x , y ) ) NEW_LINE DEDENT