Find the kth smallest number with sum of digits as m | Javascript implementation of the approach ; Recursively moving to add all the numbers upto a limit with sum of digits as m ; Max number of digits allowed in a number for this implementation ; Function to return the kth number with sum of digits as m ; The kth smallest number is found ; Driver code
let N = 2005 ; let ans = new Set ( ) ; function dfs ( num , left , ct ) { if ( ct >= 15 ) return ; if ( left == 0 ) ans . add ( num ) ; for ( let i = 0 ; i <= Math . min ( left , 9 ) ; i ++ ) dfs ( num * 10 + i , left - i , ct + 1 ) ; } function getKthNum ( m , k ) { dfs ( 0 , m , 0 ) ; let ct = 0 ; for ( let it of ans . values ( ) ) { ct ++ ; if ( ct == k ) { return it ; } } return - 1 ; } let m = 5 , k = 3 ; document . write ( getKthNum ( m , k ) ) ;