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 ; Given number and sum ; Function call
function helper ( d , s ) { let ans = [ ] ; for ( let i = 0 ; i < d ; i ++ ) { ans . push ( " " ) ; } for ( let i = d - 1 ; i >= 0 ; i -- ) { if ( s >= 9 ) { ans [ i ] = ' ' ; s -= 9 ; } else { let c = String . fromCharCode ( s + ' ' . charCodeAt ( 0 ) ) ; ans [ i ] = c ; s = 0 ; } } return ans . join ( " " ) ; } function findMin ( x , Y ) { let y = Y . toString ( ) ; let n = y . length ; let p = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { p . push ( 0 ) ; } for ( let i = 0 ; i < n ; i ++ ) { p [ i ] = y [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; if ( i > 0 ) { p [ i ] = p [ i ] + p [ i - 1 ] ; } } for ( let i = n - 1 , k = 0 ; ; i -- , k ++ ) { let d = 0 ; if ( i >= 0 ) { d = y [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; } for ( let j = d + 1 ; j <= 9 ; j ++ ) { let r = j ; if ( i > 0 ) { r += p [ i - 1 ] ; } if ( x - r >= 0 && x - r <= 9 * k ) { let suf = helper ( k , x - r ) ; let pre = " " ; if ( i > 0 ) pre = y . substring ( 0 , i ) ; let cur = String . fromCharCode ( j + ' ' . charCodeAt ( 0 ) ) ; pre += cur ; return pre + suf ; } } } } let x = 18 ; let y = 99 ; document . write ( findMin ( x , y ) ) ;