Count quadruples of given type from given array | Javascript 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
let maxN = 2002 ; let lcount = new Array ( maxN ) ; let rcount = new Array ( maxN ) ; for ( let i = 0 ; i < maxN ; i ++ ) { lcount [ i ] = new Array ( maxN ) ; rcount [ i ] = new Array ( maxN ) ; for ( let j = 0 ; j < maxN ; j ++ ) { lcount [ i ] [ j ] = 0 ; rcount [ i ] [ j ] = 0 ; } } function fill_counts ( a , n ) { let i , j ; let maxA = a [ 0 ] ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > maxA ) { maxA = a [ i ] ; } } for ( i = 0 ; i < n ; i ++ ) { lcount [ a [ i ] ] [ i ] = 1 ; rcount [ a [ i ] ] [ i ] = 1 ; } for ( i = 0 ; i <= maxA ; i ++ ) { for ( j = 1 ; j < n ; j ++ ) { lcount [ i ] [ j ] = lcount [ i ] [ j - 1 ] + lcount [ i ] [ j ] ; } for ( j = n - 2 ; j >= 0 ; j -- ) { rcount [ i ] [ j ] = rcount [ i ] [ j + 1 ] + rcount [ i ] [ j ] ; } } } function countSubsequence ( a , n ) { let i , j ; fill_counts ( a , n ) ; let answer = 0 ; for ( i = 1 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n - 1 ; j ++ ) { answer += lcount [ a [ j ] ] [ i - 1 ] * rcount [ a [ i ] ] [ j + 1 ] ; } } return answer ; } let a = [ 1 , 2 , 3 , 2 , 1 , 3 , 2 ] ; document . write ( countSubsequence ( a , a . length ) ) ;