Count Possible Decodings of a given Digit Sequence in O ( N ) time and Constant Auxiliary space | A Dynamic Programming based function to count decodings in digit sequence ; For base condition "01123" should return 0 ; Using last two calculated values , calculate for ith index ; Change bool to int ; Return the required answer ; Driver Code ; Function call
function countDecodingDP ( digits , n ) { if ( digits [ 0 ] == ' ' ) return 0 ; var count0 = 1 , count1 = 1 , count2 ; for ( var i = 2 ; i <= n ; i ++ ) { count2 = ( ( digits [ i - 1 ] != ' ' ) * count1 ) + ( ( digits [ i - 2 ] == ' ' ) || ( digits [ i - 2 ] == ' ' && digits [ i - 1 ] < ' ' ) ) * count0 ; count0 = count1 ; count1 = count2 ; } return count1 ; } var digits = " " ; var n = digits . length ; document . write ( countDecodingDP ( digits , n ) ) ;