Count quadruples of given type from given array | Python3 program of the above approach ; lcount [ i ] [ j ] : Stores the count of i on left of index j ; rcount [ i ] [ j ] : Stores the count of i on right of index j ; Function to count unique elements on left and right of any index ; Find the maximum array element ; Calculate prefix sum of counts of each value ; Calculate suffix sum of counts of each value ; Function to count quadruples of the required type ; Driver Code
maxN = 2002 NEW_LINE lcount = [ [ 0 for i in range ( maxN ) ] for j in range ( maxN ) ] NEW_LINE rcount = [ [ 0 for i in range ( maxN ) ] for j in range ( maxN ) ] NEW_LINE def fill_counts ( a , n ) : NEW_LINE INDENT maxA = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > maxA ) : NEW_LINE INDENT maxA = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT lcount [ a [ i ] ] [ i ] = 1 NEW_LINE rcount [ a [ i ] ] [ i ] = 1 NEW_LINE DEDENT for i in range ( maxA + 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT lcount [ i ] [ j ] = ( lcount [ i ] [ j - 1 ] + lcount [ i ] [ j ] ) NEW_LINE DEDENT for j in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT rcount [ i ] [ j ] = ( rcount [ i ] [ j + 1 ] + rcount [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT def countSubsequence ( a , n ) : NEW_LINE INDENT fill_counts ( a , n ) NEW_LINE answer = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT answer += ( lcount [ a [ j ] ] [ i - 1 ] * rcount [ a [ i ] ] [ j + 1 ] ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT a = [ 1 , 2 , 3 , 2 , 1 , 3 , 2 ] NEW_LINE print ( countSubsequence ( a , 7 ) ) NEW_LINE