Count pairs in an array that hold i+j= arr[i]+arr[j]
Last Updated :
17 Oct, 2022
Given an array of integers arr[], the task is to count all the pairs (arr[i], arr[j]) such that i + j = arr[i] + arr[j] for all 0 ? i < j < n.
Note: Pairs (x, y) and (y, x) are considered a single pair.
Examples:
Input: arr[] = {8, 4, 2, 1, 5, 4, 2, 1, 2, 3}
Output: 1
The only possible pair is (arr[4], arr[5]) i.e. (5, 4)
i + j = arr[i] + arr[j] => 4 + 5 = 5 + 4
Input: arr[] = {1, 0, 3, 2}
Output: 4
Naive Approach: Run two nested loops and check every possible pair for the condition where i + j = arr[i] + arr[j]. If the condition is satisfied, then update the count = count + 1. Print the count at the end.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int CountPairs( int arr[], int n)
{
int count = 0;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
if ((i + j) == (arr[i] + arr[j]))
count++;
}
}
return count;
}
int main()
{
int arr[] = { 1, 0, 3, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << CountPairs(arr, n);
return 0;
}
|
Java
public class GFG {
static int CountPairs( int arr[], int n)
{
int count = 0 ;
for ( int i = 0 ; i < n - 1 ; i++) {
for ( int j = i + 1 ; j < n; j++) {
if ((i + j) == (arr[i] + arr[j]))
count++;
}
}
return count;
}
public static void main(String args[])
{
int arr[] = { 1 , 0 , 3 , 2 };
int n = arr.length ;
System.out.print(CountPairs(arr, n));
}
}
|
Python3
def CountPairs(arr, n):
count = 0 ;
for i in range (n - 1 ):
for j in range (i + 1 , n):
if ((i + j) = = (arr[i] + arr[j])):
count + = 1 ;
return count;
arr = [ 1 , 0 , 3 , 2 ];
n = len (arr);
print (CountPairs(arr, n));
|
C#
using System;
public class GFG {
static int CountPairs( int [] arr, int n)
{
int count = 0;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
if ((i + j) == (arr[i] + arr[j]))
count++;
}
}
return count;
}
public static void Main()
{
int [] arr = { 1, 0, 3, 2 };
int n = arr.Length ;
Console.Write(CountPairs(arr, n));
}
}
|
PHP
<?php
function CountPairs(& $arr , $n )
{
$count = 0;
for ( $i = 0; $i < $n - 1; $i ++)
{
for ( $j = $i + 1; $j < $n ; $j ++)
{
if (( $i + $j ) == ( $arr [ $i ] + $arr [ $j ]))
$count ++;
}
}
return $count ;
}
$arr = array (1, 0, 3, 2 );
$n = sizeof( $arr );
echo (CountPairs( $arr , $n ));
?>
|
Javascript
<script>
function CountPairs(arr,n)
{
let count = 0;
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
if ((i + j) == (arr[i] + arr[j]))
count++;
}
}
return count;
}
let arr=[1, 0, 3, 2];
let n = arr.length ;
document.write(CountPairs(arr, n));
</script>
|
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach:
- Reduce i + j = arr[i] + arr[j] to (arr[i] – i) = -(arr[j] – j). Now, the problem is reduced to finding all the pairs of the form (x, -x).
- So, update all the elements of the array as arr[i] = arr[i] – i according to the reduction from step 1.
- In order to count all the pairs of the form (x, -x), save the frequencies of all the negative elements into a HashMap named negMap and of all the positive elements (including 0) into posMap.
- Now, for every frequency in posMap say x, find the frequency of -x in negMap. So, all the possible pairs between x and -x will be count = count + (frequency(x) * frequency(-x)).
- Print the count at the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int countValidPairs( int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
arr[i] -= i;
unordered_map< int , int > negMap;
map< int , int > posMap;
for (i = 0; i < n; i++) {
if (arr[i] < 0) {
if (negMap.count(arr[i]))
negMap.insert(
{ arr[i],
negMap.find(arr[i])->second + 1 });
else
negMap.insert({ arr[i], 1 });
}
else {
if (posMap.count(arr[i]))
posMap.insert(
{ arr[i],
posMap.find(arr[i])->second + 1 });
else
posMap.insert({ arr[i], 1 });
}
}
int count = 0;
for ( auto itr = posMap.begin(); itr != posMap.end();
++itr) {
int posVal = itr->second;
if (negMap.count(-itr->first)) {
int negVal = negMap.find(-itr->first)->second;
count += (negVal * posVal);
}
}
return count;
}
int main()
{
int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countValidPairs(arr, n);
}
|
Java
import java.util.HashMap;
import java.util.Map;
public class GFG {
static int countValidPairs( int arr[], int n)
{
int i;
for (i = 0 ; i < n; i++)
arr[i] -= i;
Map<Integer, Integer> negMap = new HashMap<>();
Map<Integer, Integer> posMap = new HashMap<>();
for (i = 0 ; i < n; i++) {
if (arr[i] < 0 ) {
if (negMap.containsKey(arr[i]))
negMap.put(arr[i], negMap.get(arr[i]) + 1 );
else
negMap.put(arr[i], 1 );
}
else {
if (posMap.containsKey(arr[i]))
posMap.put(arr[i], posMap.get(arr[i]) + 1 );
else
posMap.put(arr[i], 1 );
}
}
int count = 0 ;
for ( int posKey : posMap.keySet()) {
int posVal = posMap.get(posKey);
if (negMap.containsKey(-posKey)) {
int negVal = negMap.get(-posKey);
count += (negVal * posVal);
}
}
return count;
}
public static void main(String[] args)
{
int arr[] = { 8 , 4 , 2 , 1 , 5 , 4 , 2 , 1 , 2 , 3 };
int n = arr.length;
System.out.println(countValidPairs(arr, n));
}
}
|
Python3
def countValidPairs(arr, n):
i = 0
for i in range (n):
arr[i] - = i
negMap = dict ()
posMap = dict ()
for i in range (n):
if (arr[i] < 0 ):
negMap[arr[i]] = negMap.get(arr[i], 0 ) + 1
else :
posMap[arr[i]] = posMap.get(arr[i], 0 ) + 1
count = 0
for posKey in posMap:
posVal = posMap[posKey]
negVal = 0
if - posKey in negMap:
negVal = negMap[ - posKey]
count + = (negVal * posVal)
return count
arr = [ 8 , 4 , 2 , 1 , 5 , 4 , 2 , 1 , 2 , 3 ]
n = len (arr)
print (countValidPairs(arr, n))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static int countValidPairs( int []arr,
int n)
{
int i;
for (i = 0; i < n; i++)
arr[i] -= i;
Dictionary< int ,
int > negMap =
new Dictionary< int ,
int >();
Dictionary< int ,
int > posMap =
new Dictionary< int ,
int >();
for (i = 0; i < n; i++)
{
if (arr[i] < 0)
{
if (negMap.ContainsKey(arr[i]))
negMap[arr[i]] = negMap[arr[i]] + 1;
else
negMap.Add(arr[i], 1);
}
else
{
if (posMap.ContainsKey(arr[i]))
posMap.Add(arr[i], posMap[arr[i]] + 1);
else
posMap.Add(arr[i], 1);
}
}
int count = 0;
foreach ( int posKey in posMap.Keys)
{
int posVal = posMap[posKey];
if (negMap.ContainsKey(-posKey))
{
int negVal = negMap[-posKey];
count += (negVal * posVal);
}
}
return count;
}
public static void Main(String[] args)
{
int []arr = {8, 4, 2, 1, 5,
4, 2, 1, 2, 3};
int n = arr.Length;
Console.WriteLine(countValidPairs(arr, n));
}
}
|
Javascript
<script>
function countValidPairs(arr,n)
{
let i;
for (i = 0; i < n; i++)
arr[i] -= i;
let negMap = new Map();
let posMap = new Map();
for (i = 0; i < n; i++) {
if (arr[i] < 0) {
if (negMap.has(arr[i]))
negMap.set(arr[i], negMap.get(arr[i]) + 1);
else
negMap.set(arr[i], 1);
}
else {
if (posMap.has(arr[i]))
posMap.set(arr[i], posMap.get(arr[i]) + 1);
else
posMap.set(arr[i], 1);
}
}
let count = 0;
for (let posKey of posMap.keys()) {
let posVal = posMap.get(posKey);
if (negMap.has(-posKey)) {
let negVal = negMap.get(-posKey);
count += (negVal * posVal);
}
}
return count;
}
let arr=[8, 4, 2, 1, 5, 4, 2, 1, 2, 3];
let n = arr.length;
document.write(countValidPairs(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...