VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-quadruples-of-given-type-from-given-array/

⇱ Count quadruples of given type from given array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count quadruples of given type from given array

Last Updated : 15 Jul, 2025

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:


Output: 
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:

  • Maintain two arrays lcount[i][j] and rcount[i][j] which stores the count of the element i in the indices less than j and rcount[i][j] stores the count of the element i in the indices greater than j.
  • Iterate over the nested loop from 1 to N and find all the subsequence of type XYXY
answer += lcount[a[i]][j-1] * rcount[a[j]][i-1]


Below is the implementation of the above approach: 


Output: 
5

 

Time Complexity: O(N2)
Auxiliary Space: O(N2)

Comment