Count of sub | Python3 implementation of the approach ; 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
MOD = 1000000007 NEW_LINE def solve ( test ) : NEW_LINE INDENT size = len ( test ) NEW_LINE total = 0 NEW_LINE for i in range ( 9 ) : NEW_LINE INDENT x = i NEW_LINE y = i + 1 NEW_LINE newtest = " " NEW_LINE for j in range ( size ) : NEW_LINE INDENT if ( ord ( test [ j ] ) == x + 48 or ord ( test [ j ] ) == y + 48 ) : NEW_LINE INDENT newtest += test [ j ] NEW_LINE DEDENT DEDENT if ( len ( newtest ) > 0 ) : NEW_LINE INDENT size1 = len ( newtest ) NEW_LINE prefix = [ 0 for i in range ( size1 ) ] NEW_LINE for j in range ( size1 ) : NEW_LINE INDENT if ( ord ( newtest [ j ] ) == y + 48 ) : NEW_LINE INDENT prefix [ j ] += 1 NEW_LINE DEDENT DEDENT for j in range ( 1 , size1 ) : NEW_LINE INDENT prefix [ j ] += prefix [ j - 1 ] NEW_LINE DEDENT count = 0 NEW_LINE firstcount = 0 NEW_LINE ss = 0 NEW_LINE prev = 0 NEW_LINE for j in range ( size1 ) : NEW_LINE INDENT if ( ord ( newtest [ j ] ) == x + 48 ) : NEW_LINE INDENT count += 1 NEW_LINE firstcount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ss += count * count NEW_LINE pairsum = ( firstcount * firstcount - ss ) // 2 NEW_LINE temp = pairsum NEW_LINE pairsum -= prev NEW_LINE prev = temp NEW_LINE secondway = prefix [ size1 - 1 ] NEW_LINE if ( j != 0 ) : NEW_LINE INDENT secondway -= prefix [ j - 1 ] NEW_LINE DEDENT answer = count * ( count - 1 ) * secondway * ( secondway - 1 ) NEW_LINE answer //= 4 NEW_LINE answer += ( pairsum * secondway * ( secondway - 1 ) ) // 2 NEW_LINE total += answer NEW_LINE count = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT return total NEW_LINE DEDENT test = "13134422" NEW_LINE print ( solve ( test ) ) NEW_LINE