Given an array arr[] consisting of N integers, the task is to find the total number of unordered pairs (i, j) in the array such that arr[i] is equal to arr[j] and i < j for all subarrays of the given array.
Examples:
Input: arr[] = {1, 2, 1, 1}
Output: 6
Explanation: All subarrays of the given array of size greater than 1 are:
- {1, 2}: There are no such pairs satisfying the given criteria. Hence, the count of pairs for the current subarray is 0.
- {2, 1}: There are no such pairs satisfying the given criteria. Hence, the count of pairs for the current subarray is 0.
- {1, 1}: The pairs satisfying the given criteria are (0, 1). Hence, the count of pairs for the current subarray is 1.
- {1, 2, 1}: The pairs satisfying the given criteria are (0, 2). Hence, the count of pairs for the current subarray is 1.
- {2, 1, 1}: The pairs satisfying the given criteria are (1, 1). Hence, the count of pairs for the current subarray is 1.
- {1, 2, 1, 1}: The pairs satisfying the given criteria are (0, 2), (0, 3), and (2, 3). Hence, the count of pairs for the current subarray is 3.
Therefore, the total count from all the subarrays = 1 + 1 + 1 + 3 = 6.
Input: arr[] = {1, 2, 1, 3}
Output: 2
Naive Approach: The simplest approach to solve the given problem is to generate all possible subarrays of the size greater than 1, and find the sum of the count of pairs satisfying the given criteria for all possible subarrays of the given array.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can also be optimized by storing all positions corresponding to each distinct element in a Map and then, for each element, traverse the positions corresponding to that element and calculate the number of subarrays in which each pair occurs. Follow the steps below to solve the problem:
- Initialize a map M as having keys as a pair and values as a vector.
- Initialize another variable, say ans as 0 that stores the total count of pairs satisfying the given criteria.
- Traverse the given array arr[] using the variable i and append the value of i to the key M[arr[i]].
- Traverse the map M and perform the following steps:
- Initialize a vector, say V as the value corresponding to the current key.
- Initialize a variable, say sum as 0.
- Traverse the given vector V for each element V[j] add the value of (sum*(N – V[j])) to the variable ans and add the value (V[j] + 1) to the variable sum.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void countPairs(vector< int > arr)
{
int N = arr.size();
int ans = 0;
map< int , vector< int > > M;
for ( int i = 0;
i < arr.size(); i++) {
M[arr[i]].push_back(i);
}
for ( auto it : M) {
vector< int > v = it.second;
int sum = 0;
for ( int j = 0;
j < v.size(); j++) {
ans += sum * (N - v[j]);
sum += v[j] + 1;
}
}
cout << ans;
}
int main()
{
vector< int > arr = { 1, 2, 1, 1 };
countPairs(arr);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
import java.util.List;
import com.google.common.collect.*;
class GFG {
static void countPairs( int [] arr)
{
int N = arr.length;
int ans = 0 ;
ListMultimap<Integer, Integer> M = ArrayListMultimap.create();
for ( int i = 0 ;
i < arr.length; i++) {
M.put(arr[i], i);
}
for (var it: M.keySet()) {
List<Integer> v = M.get(it);
int sum = 0 ;
for ( int j : v) {
ans += sum * (N - j);
sum += j + 1 ;
}
}
System.out.println(ans);
}
public static void main (String[] args) {
int [] arr = { 1 , 2 , 1 , 1 };
countPairs(arr);
}
}
|
Python3
def countPairs(arr):
N = len (arr)
ans = 0
M = {}
for i in range ( len (arr)):
if arr[i] in M:
M[arr[i]].append(i)
else :
M[arr[i]] = [i]
for key, value in M.items():
v = value
sum1 = 0
for j in range ( len (v)):
ans + = (sum1 * (N - v[j]))
sum1 + = v[j] + 1
print (ans)
if __name__ = = '__main__' :
arr = [ 1 , 2 , 1 , 1 ]
countPairs(arr)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void countPairs( int [] arr)
{
int N = arr.Length;
int ans = 0;
Dictionary< int , List< int >> M = new Dictionary< int , List< int >>();
for ( int i = 0 ; i < arr.Length ; i++) {
if (!M.ContainsKey(arr[i])){
M.Add(arr[i], new List< int >());
}
M[arr[i]].Add(i);
}
foreach (KeyValuePair< int , List< int >> it in M) {
List< int > v = it.Value;
int sum = 0;
foreach ( int j in v) {
ans += sum * (N - j);
sum += j + 1;
}
}
Console.Write(ans);
}
public static void Main( string [] args){
int [] arr = new int []{ 1, 2, 1, 1 };
countPairs(arr);
}
}
|
Javascript
<script>
function countPairs(arr) {
let N = arr.length;
let ans = 0;
let M = new Map();
for (let i = 0; i < arr.length; i++) {
if (M.has(arr[i])) {
M.get(arr[i]).push(i);
} else {
M.set(arr[i], [i])
}
}
for (let it of M) {
let v = it[1];
let sum = 0;
for (let j = 0; j < v.length; j++) {
ans += sum * (N - v[j]);
sum += v[j] + 1;
}
}
document.write(ans);
}
let arr = [1, 2, 1, 1];
countPairs(arr);
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(N)