Count of sub | Function to return the total required sub - sequences ; Find ways for all values of x ; x + 1 ; Removing all unnecessary digits ; Prefix Sum Array for X + 1 digit ; Sum of squares ; Previous sum of all possible pairs ; To find sum of multiplication of all possible pairs ; To prevent overcounting ; Adding ways for all possible x ; Driver code
function solve ( test , MOD ) { let size = test . length ; let total = 0 ; for ( let i = 0 ; i <= 8 ; i ++ ) { let x = i ; let y = i + 1 ; let newtest = " " ; for ( let j = 0 ; j < size ; j ++ ) { if ( test [ j ] . charCodeAt ( 0 ) == x + 48 || test [ j ] . charCodeAt ( 0 ) == y + 48 ) { newtest += test [ j ] ; } } if ( newtest . length > 0 ) { let size1 = newtest . length ; let prefix = new Array ( size1 ) ; for ( let j = 0 ; j < size1 ; j ++ ) { prefix [ j ] = 0 ; if ( newtest [ j ] . charCodeAt ( 0 ) == y + 48 ) { prefix [ j ] ++ ; } } for ( let j = 1 ; j < size1 ; j ++ ) { prefix [ j ] += prefix [ j - 1 ] ; } let count = 0 ; let firstcount = 0 ; let ss = 0 ; let prev = 0 ; for ( let j = 0 ; j < size1 ; j ++ ) { if ( newtest [ j ] . charCodeAt ( 0 ) == x + 48 ) { count ++ ; firstcount ++ ; } else { ss += count * count ; let pairsum = Math . floor ( ( firstcount * firstcount - ss ) / 2 ) ; let temp = pairsum ; pairsum -= prev ; prev = temp ; let secondway = prefix [ size1 - 1 ] ; if ( j != 0 ) secondway -= prefix [ j - 1 ] ; let answer = count * ( count - 1 ) * secondway * ( secondway - 1 ) ; answer = Math . floor ( answer / 4 ) ; answer += Math . floor ( ( pairsum * secondway * ( secondway - 1 ) ) / 2 ) ; total += answer ; count = 0 ; } } } } return total ; } let test = " " ; let MOD = 1000000007 ; document . write ( solve ( test , MOD ) ) ;