Count quadruples (i, j, k, l) in an array such that i < j < k < l and arr[i] = arr[k] and arr[j] = arr[l]

Given an array arr[] consisting of N integers, the task is to count the number of tuples (i, j, k, l) from the given array such that i < j < k < l and arr[i] = arr[k] and arr[j] = arr[l].
Examples:
Input: arr[] = {1, 2, 1, 2, 2, 2}Â
Output: 4Â
Explanation:Â
The tuples which satisfy the given condition are:Â
1) (0, 1, 2, 3) since arr[0] = arr[2] = 1 and arr[1] = arr[3] = 2Â
2) (0, 1, 2, 4) since arr[0] = arr[2] = 1 and arr[1] = arr[4] = 2Â
3) (0, 1, 2, 5) since arr[0] = arr[2] = 1 and arr[1] = arr[5] = 2Â
4) (1, 3, 4, 5) since arr[1] = arr[4] = 2 and arr[3] = arr[5] = 2Input: arr[] = {2, 5, 2, 2, 5, 4}Â
Output: 2
Naive Approach: The simplest approach is to generate all the possible quadruples and check if the given condition holds true. If found to be true, then increase the final count. Print the final count obtained.
Time Complexity: O(N4)Â
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Hashing. Below are the steps:
- For each index j iterate to find a pair of indices (j, l) such that arr[j] = arr[l] and j < l.
- Use a hash table to keep count of the frequency of all array elements present in the indices [0, j – 1].
- While traversing through index j to l, simply add the frequency of each element between j and l to the final count.
- Repeat this process for every such possible pair of indices (j, l).
- Print the total count of quadruples after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to count total number// of required tuplesint countTuples(int arr[], int N){Â Â Â Â int ans = 0, val = 0;Â
    // Initialize unordered map    unordered_map<int, int> freq;Â
    for (int j = 0; j < N - 2; j++) {        val = 0;Â
        // Find the pairs (j, l) such        // that arr[j] = arr[l] and j < l        for (int l = j + 1; l < N; l++) {Â
            // elements are equal            if (arr[j] == arr[l]) {Â
                // Update the count                ans += val;            }Â
            // Add the frequency of            // arr[l] to val            val += freq[arr[l]];        }Â
        // Update the frequency of        // element arr[j]        freq[arr[j]]++;    }Â
    // Return the answer    return ans;}Â
// Driver codeint main(){Â Â Â Â // Given array arr[]Â Â Â Â int arr[] = { 1, 2, 1, 2, 2, 2 };Â
    int N = sizeof(arr) / sizeof(arr[0]);Â
    // Function Call    cout << countTuples(arr, N);Â
    return 0;} |
Java
// Java program for // the above approachimport java.util.*;class GFG{Â
// Function to count total number// of required tuplesstatic int countTuples(int arr[], Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â int N){Â Â int ans = 0, val = 0;Â
  // Initialize unordered map  HashMap<Integer,          Integer> freq = new HashMap<Integer,                                      Integer>();Â
  for (int j = 0; j < N - 2; j++)   {    val = 0;Â
    // Find the pairs (j, l) such    // that arr[j] = arr[l] and j < l    for (int l = j + 1; l < N; l++)     {      // elements are equal      if (arr[j] == arr[l])       {        // Update the count        ans += val;      }Â
      // Add the frequency of      // arr[l] to val      if(freq.containsKey(arr[l]))        val += freq.get(arr[l]);    }Â
    // Update the frequency of    // element arr[j]    if(freq.containsKey(arr[j]))    {      freq.put(arr[j], freq.get(arr[j]) + 1);    }    else    {      freq.put(arr[j], 1);    }  }Â
  // Return the answer  return ans;}Â
// Driver codepublic static void main(String[] args){Â Â // Given array arr[]Â Â int arr[] = {1, 2, 1, 2, 2, 2};Â Â int N = arr.length;Â
  // Function Call  System.out.print(countTuples(arr, N));}}Â
// This code is contributed by Rajput-Ji |
Python3
# Python3 program for the above approachÂ
# Function to count total number# of required tuplesdef countTuples(arr, N):Â Â Â Â Â Â Â Â Â ans = 0Â Â Â Â val = 0Â
    # Initialize unordered map    freq = {}Â
    for j in range(N - 2):        val = 0Â
        # Find the pairs (j, l) such        # that arr[j] = arr[l] and j < l        for l in range(j + 1, N):Â
            # Elements are equal            if (arr[j] == arr[l]):Â
                # Update the count                ans += valÂ
            # Add the frequency of            # arr[l] to val            if arr[l] in freq:                val += freq[arr[l]]Â
        # Update the frequency of        # element arr[j]        freq[arr[j]] = freq.get(arr[j], 0) + 1Â
    # Return the answer    return ansÂ
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â # Given array arr[]Â Â Â Â arr = [ 1, 2, 1, 2, 2, 2 ]Â
    N = len(arr)Â
    # Function call    print(countTuples(arr, N))Â
# This code is contributed by mohit kumar 29 |
C#
// C# program for the above approachusing System;using System.Collections.Generic;Â
class GFG{Â
// Function to count total number// of required tuplesstatic int countTuples(int []arr,                        int N){    int ans = 0, val = 0;         // Initialize unordered map    Dictionary<int,               int> freq = new Dictionary<int,                                          int>();         for(int j = 0; j < N - 2; j++)     {        val = 0;                 // Find the pairs (j, l) such        // that arr[j] = arr[l] and j < l        for(int l = j + 1; l < N; l++)         {                         // Elements are equal            if (arr[j] == arr[l])             {                                 // Update the count                ans += val;            }                         // Add the frequency of            // arr[l] to val            if (freq.ContainsKey(arr[l]))                val += freq[arr[l]];        }                 // Update the frequency of        // element arr[j]        if (freq.ContainsKey(arr[j]))        {            freq[arr[j]] = freq[arr[j]] + 1;        }        else        {            freq.Add(arr[j], 1);        }    }         // Return the answer    return ans;}Â
// Driver codepublic static void Main(String[] args){         // Given array []arr    int []arr = { 1, 2, 1, 2, 2, 2 };    int N = arr.Length;         // Function call    Console.Write(countTuples(arr, N));}}Â
// This code is contributed by Amit Katiyar |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to count total number// of required tuplesfunction countTuples(arr, N){Â Â Â Â var ans = 0, val = 0;Â
    // Initialize unordered map    var freq = new Map();Â
    for(var j = 0; j < N - 2; j++)     {        val = 0;Â
        // Find the pairs (j, l) such        // that arr[j] = arr[l] and j < l        for(var l = j + 1; l < N; l++)         {                         // Elements are equal            if (arr[j] == arr[l])            {                                 // Update the count                ans += val;            }Â
            // Add the frequency of            // arr[l] to val            if (freq.has(arr[l]))            {                val += freq.get(arr[l]);            }        }Â
        // Update the frequency of        // element arr[j]        if (freq.has(arr[j]))        {            freq.set(arr[j], freq.get(arr[j]) + 1);        }        else        {            freq.set(arr[j], 1);        }    }Â
    // Return the answer    return ans;}Â
// Driver codeÂ
// Given array arr[]var arr = [ 1, 2, 1, 2, 2, 2 ];var N = arr.length;Â
// Function Calldocument.write(countTuples(arr, N));Â
// This code is contributed by rutvik_56Â
</script> |
4
Time Complexity: O(N2)Â
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



