Total count of sorted numbers upto N digits in range [ L , R ] ( Magnificent necklace combinatorics problem ) | Function to count total number of ways ; Stores all DP - states ; Stores the result ; Traverse the range [ 0 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Assign dp [ 0 ] [ R - L ] to ans ; Traverse the range [ 1 , N ] ; Traverse the range [ 1 , R - L ] ; Update dp [ i ] [ j ] ; Increment ans by dp [ i - 1 ] [ j ] ; Return ans ; Input ; Function call
function Count ( N , L , R ) { let dp = new Array ( N ) . fill ( 0 ) . map ( ( ) => new Array ( R - L + 1 ) . fill ( 0 ) ) ; let ans = 0 ; for ( let i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; } for ( let i = 1 ; i < dp [ 0 ] . length ; i ++ ) { dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 1 ; } ans = dp [ 0 ] [ R - L ] ; for ( let i = 1 ; i < N ; i ++ ) { for ( let j = 1 ; j < dp [ 0 ] . length ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ; } ans += dp [ i ] [ R - L ] ; } return ans ; } let N = 3 ; let L = 6 ; let R = 9 ; document . write ( Count ( N , L , R ) ) ;