Count of subsequences of length 4 in form ( x , x , x + 1 , x + 1 ) | Set 2 | Function to count the numbers ; Array that stores the digits from left to right ; Array that stores the digits from right to left ; Initially both array store zero ; Fill the table for count1 array ; Update the count of current character ; Fill the table for count2 array ; Update the count of cuuent character ; Variable that stores the count of the numbers ; Traverse Input string and get the count of digits from count1 and count2 array such that difference b / w digit is 1 & store it int c1 & c2 . And store it in variable c1 and c2 ; Update the ans ; Return the final count ; Given String ; Function call
def countStableNum ( Str , N ) : NEW_LINE INDENT count1 = [ [ 0 for j in range ( 10 ) ] for i in range ( N ) ] NEW_LINE count2 = [ [ 0 for j in range ( 10 ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count1 [ i ] [ j ] , count2 [ i ] [ j ] = 0 , 0 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count1 [ i ] [ j ] = ( count1 [ i ] [ j ] + count1 [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT count1 [ i ] [ ord ( Str [ i ] ) - ord ( '0' ) ] += 1 NEW_LINE DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i != N - 1 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count2 [ i ] [ j ] += count2 [ i + 1 ] [ j ] NEW_LINE DEDENT DEDENT count2 [ i ] [ ord ( Str [ i ] ) - ord ( '0' ) ] = count2 [ i ] [ ord ( Str [ i ] ) - ord ( '0' ) ] + 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT if ( Str [ i ] == '9' ) : NEW_LINE INDENT continue NEW_LINE DEDENT c1 = count1 [ i - 1 ] [ ord ( Str [ i ] ) - ord ( '0' ) ] NEW_LINE c2 = count2 [ i + 1 ] [ ord ( Str [ i ] ) - ord ( '0' ) + 1 ] NEW_LINE if ( c2 == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans = ( ans + ( c1 * ( ( c2 * ( c2 - 1 ) // 2 ) ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT Str = "224353" NEW_LINE N = len ( Str ) NEW_LINE print ( countStableNum ( Str , N ) ) NEW_LINE