Count pairs in an array that hold i+j= arr[i]+arr[j] - GeeksforGeeks

31 May, 2021
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++
Java
Python3
C#
PHP
Javascript
// C++ program to count all the pairs that// hold the condition i + j = arr[i] + arr[j]#include <iostream>using namespace std; // Function to return the count of pairs that// satisfy the given conditionint CountPairs(int arr[], int n){    int count = 0;     // Generate all possible pairs and increment    // the count if the condition is satisfied    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;} // Driver codeint main(){    int arr[] = { 1, 0, 3, 2 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << CountPairs(arr, n);    return 0;}
// Java program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] public class GFG {         // Function to return the count of pairs that    // satisfy the given condition    static int CountPairs(int arr[], int n)    {        int count = 0;             // Generate all possible pairs and increment        // the count if the condition is satisfied        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;    }         // Driver code    public static void main(String args[])    {        int arr[] = { 1, 0, 3, 2 };        int n = arr.length ;        System.out.print(CountPairs(arr, n));    }     // This code is contributed by Ryuga.}
# Python 3 program to count all the pairs that# hold the condition i + j = arr[i] + arr[j] # Function to return the count of pairs# that satisfy the given conditiondef CountPairs(arr, n):     count = 0;     # Generate all possible pairs and increment    # the count if the condition is satisfied    for i in range(n - 1):        for j in range(i + 1, n):            if ((i + j) == (arr[i] + arr[j])):                count += 1;    return count; # Driver codearr = [ 1, 0, 3, 2 ];n = len(arr);print(CountPairs(arr, n)); # This code is contributed# by Akanksha Rai
using System; // C# program to count all the pairs that// hold the condition i + j = arr[i] + arr[j]  public class GFG {          // Function to return the count of pairs that    // satisfy the given condition    static int CountPairs(int[] arr, int n)    {        int count = 0;              // Generate all possible pairs and increment        // the count if the condition is satisfied        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;    }          // Driver code    public static void Main()    {        int[] arr = { 1, 0, 3, 2 };        int n = arr.Length ;        Console.Write(CountPairs(arr, n));    }  }
<?php// PHP program to count all the pairs that// hold the condition i + j = arr[i] + arr[j] // Function to return the count of pairs// that satisfy the given conditionfunction CountPairs(&$arr, $n){    $count = 0;     // Generate all possible pairs and increment    // the count if the condition is satisfied    for ($i = 0; $i < $n - 1; $i++)    {        for ($j = $i + 1; $j < $n; $j++)        {            if (($i + $j) == ($arr[$i] + $arr[$j]))                $count++;        }    }    return $count;} // Driver code$arr = array(1, 0, 3, 2 );$n = sizeof($arr);echo(CountPairs($arr, $n)); // This code is contributed// by Shivi_Aggarwal?>
<script>// Javascript program to count all the pairs that// hold the condition i + j = arr[i] + arr[j]         // Function to return the count of pairs that    // satisfy the given condition    function CountPairs(arr,n)    {        let count = 0;              // Generate all possible pairs and increment        // the count if the condition is satisfied        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;    }         // Driver code    let arr=[1, 0, 3, 2];    let n = arr.length ;    document.write(CountPairs(arr, n));  // This code is contributed by avanitrachhadiya2155</script>
4
 
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.
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++
Java
Python3
C#
Javascript
#include <iostream>#include <bits/stdc++.h>using namespace std; // Function to return the count of pairs that// satisfy the given conditionint countValidPairs(int arr[], int n){     int i;     // Update all the elements as describde    // in the approach    for (i = 0; i < n; i++)        arr[i] -= i;     // HashMap for storing the frequency of    // negative elements    map<int, int> negMap;     // HashMap for storing the frequency of    // positive elements (including 0)    map<int, int> posMap;    for (i = 0; i < n; i++)    {         // For negative elements        if (arr[i] < 0)        {             // If HashMap already contains the integer            // then increment its frequency by 1            if (negMap.count(arr[i]))                negMap.insert({arr[i], negMap.find(arr[i])->second + 1});            else                 // Else set the frequency to 1                negMap.insert({arr[i], 1});        }         // For positive elements (including 0)        else        {             // If HashMap already contains the integer            // then increment its frequency by 1            if (posMap.count(arr[i]))                posMap.insert({arr[i], posMap.find(arr[i])->second + 1});            else                 // Else set the frequency to 1                posMap.insert({arr[i], 1});        }    }     // To store the count of valid pairs    int count = 0;     for (auto itr = posMap.begin(); itr != posMap.end(); ++itr)    {        int posVal = itr->second;         // If an equivalent -ve element is found for        // the current +ve element        if (negMap.count(-itr->first))        {            int negVal = negMap.find(-itr->first)->second;             // Add all possible pairs to the count            count += (negVal * posVal);        }    }     // Return the count    return count;} // Driver codeint main(){    int arr[] = { 8, 4, 2, 1, 5, 4, 2, 1, 2, 3 };    int n = sizeof(arr) / sizeof(arr[0]);    cout << countValidPairs(arr, n);     } // This code is contributed by ApurvaRaj
import java.util.HashMap;import java.util.Map;public class GFG {     // Function to return the count of pairs that    // satisfy the given condition    static int countValidPairs(int arr[], int n)    {         int i;         // Update all the elements as describde        // in the approach        for (i = 0; i < n; i++)            arr[i] -= i;         // HashMap for storing the frequency of        // negative elements        Map<Integer, Integer> negMap = new HashMap<>();         // HashMap for storing the frequency of        // positive elements (including 0)        Map<Integer, Integer> posMap = new HashMap<>();        for (i = 0; i < n; i++) {             // For negative elements            if (arr[i] < 0) {                 // If HashMap already contains the integer                // then increment its frequency by 1                if (negMap.containsKey(arr[i]))                    negMap.put(arr[i], negMap.get(arr[i]) + 1);                else                     // Else set the frequency to 1                    negMap.put(arr[i], 1);            }             // For positive elements (including 0)            else {                 // If HashMap already contains the integer                // then increment its frequency by 1                if (posMap.containsKey(arr[i]))                    posMap.put(arr[i], posMap.get(arr[i]) + 1);                else                     // Else set the frequency to 1                    posMap.put(arr[i], 1);            }        }         // To store the count of valid pairs        int count = 0;         for (int posKey : posMap.keySet()) {            int posVal = posMap.get(posKey);             // If an equivalent -ve element is found for            // the current +ve element            if (negMap.containsKey(-posKey)) {                int negVal = negMap.get(-posKey);                 // Add all possible pairs to the count                count += (negVal * posVal);            }        }         // Return the count        return count;    }     // Driver code    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));    }}
# Function to return the count of pairs that# satisfy the given conditiondef countValidPairs(arr, n):    i = 0     # Update all the elements as described    # in the approach    for i in range(n):        arr[i] -= i     # HashMap for storing the frequency    # of negative elements    negMap = dict()     # HashMap for storing the frequency of    # positive elements (including 0)    posMap = dict()    for i in range(n):         # For negative elements        if (arr[i] < 0):                         # If HashMap already contains the integer            # then increment its frequency by 1            negMap[arr[i]] = negMap.get(arr[i], 0) + 1                 # For positive elements (including 0)        else:             # If HashMap already contains the integer            # then increment its frequency by 1            posMap[arr[i]] = posMap.get(arr[i], 0) + 1     # To store the count of valid pairs    count = 0     for posKey in posMap:        posVal = posMap[posKey]         negVal = 0         if -posKey in negMap:            negVal = negMap[-posKey]         # Add all possible pairs to the count        count += (negVal * posVal)     # Return the count    return count # Driver codearr = [8, 4, 2, 1, 5, 4, 2, 1, 2, 3]n = len(arr)print(countValidPairs(arr, n)) # This code is contributed# by mohit kumar
// C# program to implement// the above approachusing System;using System.Collections.Generic;class GFG{ // Function to return the count// of pairs that satisfy the given// conditionstatic int countValidPairs(int []arr,                           int n){  int i;   // Update all the elements  // as described in the approach  for (i = 0; i < n; i++)    arr[i] -= i;   // Dictionary for storing the  // frequency of negative elements  Dictionary<int,             int> negMap =             new Dictionary<int,                            int>();   // Dictionary for storing the  // frequency of positive elements  // (including 0)  Dictionary<int,             int> posMap =             new Dictionary<int,                            int>();  for (i = 0; i < n; i++)  {    // For negative elements    if (arr[i] < 0)    {      // If Dictionary already      // contains the integer then      // increment its frequency by 1      if (negMap.ContainsKey(arr[i]))        negMap[arr[i]] = negMap[arr[i]] + 1;      else         // Else set the frequency to 1        negMap.Add(arr[i], 1);    }     // For positive elements (including 0)    else    {      // If Dictionary already contains      // the integer then increment its      // frequency by 1      if (posMap.ContainsKey(arr[i]))        posMap.Add(arr[i], posMap[arr[i]] + 1);      else         // Else set the frequency to 1        posMap.Add(arr[i], 1);    }  }   // To store the count of valid pairs  int count = 0;   foreach (int posKey in posMap.Keys)  {    int posVal = posMap[posKey];     // If an equivalent -ve element    // is found for the current +ve element    if (negMap.ContainsKey(-posKey))    {      int negVal = negMap[-posKey];       // Add all possible pairs to      // the count      count += (negVal * posVal);    }  }   // Return the count  return count;} // Driver codepublic 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));}} // This code is contributed by Rajput-Ji
<script> // Function to return the count of pairs that// satisfy the given conditionfunction countValidPairs(arr,n){        let i;          // Update all the elements as describde        // in the approach        for (i = 0; i < n; i++)            arr[i] -= i;          // HashMap for storing the frequency of        // negative elements        let negMap = new Map();          // HashMap for storing the frequency of        // positive elements (including 0)        let posMap = new Map();        for (i = 0; i < n; i++) {              // For negative elements            if (arr[i] < 0) {                  // If HashMap already contains the integer                // then increment its frequency by 1                if (negMap.has(arr[i]))                    negMap.set(arr[i], negMap.get(arr[i]) + 1);                else                      // Else set the frequency to 1                    negMap.set(arr[i], 1);            }              // For positive elements (including 0)            else {                  // If HashMap already contains the integer                // then increment its frequency by 1                if (posMap.has(arr[i]))                    posMap.set(arr[i], posMap.get(arr[i]) + 1);                else                      // Else set the frequency to 1                    posMap.set(arr[i], 1);            }        }          // To store the count of valid pairs        let count = 0;          for (let posKey of posMap.keys()) {            let posVal = posMap.get(posKey);              // If an equivalent -ve element is found for            // the current +ve element            if (negMap.has(-posKey)) {                let negVal = negMap.get(-posKey);                  // Add all possible pairs to the count                count += (negVal * posVal);            }        }          // Return the count        return count;} // Driver codelet arr=[8, 4, 2, 1, 5, 4, 2, 1, 2, 3];let n = arr.length;document.write(countValidPairs(arr, n));       // This code is contributed by rag2127</script>
1
 
ankthon
ukasp
Shivi_Aggarwal
Akanksha_Rai
mohit kumar 29
ApurvaRaj
Rajput-Ji
avanitrachhadiya2155
rag2127
Hash
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Window Sliding Technique
Count pairs with given sum
Program to find sum of elements in a given array
Reversal algorithm for array rotation
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Hashing | Set 3 (Open Addressing)
Hashing | Set 2 (Separate Chaining)