![]() |
VOOZH | about |
Given an array arr[], the task is to find the number of quadruples of the form a[i] = a[k] and a[j] = a[l] ( 0 <= i < j < k < l <= N ) from the given array.
Examples:
Input: arr[] = {1, 2, 4, 2, 1, 5, 2}
Output: 2
Explanation: The quadruple {1, 2, 1, 2} occurs twice in the array, at indices {0, 1, 4, 6} and {0, 3, 4, 6}. Therefore, the required count is 2.Input: arr[] = {1, 2, 3, 2, 1, 3, 2}
Output: 5
Explanation: The quadruple {1, 2, 1, 2} occurs twice in the array at indices {0, 1, 4, 6} and {0, 3, 4, 6}. The quadruples {1, 3, 1, 3}, {3, 2, 3, 2} and {2, 3, 2, 3} occurs once each. Therefore, the required count is 5.
Naive Approach: The simplest approach to solve the problem is to iteratively check all combinations of 4 elements from the given array and check if it satisfies the given condition or not.
Below is the implementation of the above approach:
5
Time Complexity: O(N4)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to maintain two arrays to store the count of element X on the left and right side of every index. Follow the steps below to solve the problem:
answer += lcount[a[i]][j-1] * rcount[a[j]][i-1]
Below is the implementation of the above approach:
5
Time Complexity: O(N2)
Auxiliary Space: O(N2)