Skip to content
Related Articles

Related Articles

Count pairs in given Array having sum of index and value at that index equal

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 20 May, 2022

Given an array arr[] containing positive integers, count the total number of pairs for which arr[i]+i = arr[j]+j such that 0≤i<j≤n-1.

Examples:

Input: arr[] = { 6, 1, 4, 3 }
Output: 3
Explanation: The elements at index 0, 2, 3 has same value of a[i]+i as all sum to 6 {(6+0), (4+2), (3+3)}.

Input: arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 }
Output: 28

 

Naive Approach: The brute force approach is implemented by iterating two loops and counting all such pairs that follow arr[i]+i = arr[j]+j

Below is the implementation of the above approach:

C++




// C++ program to find Count the pair of
// elements in  an array such that
// arr[i]+i=arr[j]+j
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the
// total count of pairs
int count(int arr[], int n)
{
    int ans = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if ((arr[i] + i) == (arr[j] + j)) {
                ans++;
            }
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 6, 1, 4, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << count(arr, N);
    return 0;
}


Java




// Java program to find Count the pair of
// elements in  an array such that
// arr[i]+i=arr[j]+j
import java.io.*;
class GFG
{
 
  // Function to return the
  // total count of pairs
  static int count(int arr[], int n)
  {
    int ans = 0;
    for (int i = 0; i < n; i++) {
      for (int j = i + 1; j < n; j++) {
        if ((arr[i] + i) == (arr[j] + j)) {
          ans++;
        }
      }
    }
    return ans;
  }
 
  // Driver code
  public static void main (String[] args) {
    int arr[] = { 6, 1, 4, 3 };
    int N = arr.length;
    System.out.println(count(arr, N));
  }
}
 
// This code is contributed by hrithikgarg03188.


Python3




# python3 program to find Count the pair of
# elements in an array such that
# arr[i]+i=arr[j]+j
 
# Function to return the
# total count of pairs
def count(arr, n):
 
    ans = 0
    for i in range(0, n):
        for j in range(i + 1, n):
            if ((arr[i] + i) == (arr[j] + j)):
                ans += 1
 
    return ans
   
# Driver code
if __name__ == "__main__":
 
    arr = [6, 1, 4, 3]
    N = len(arr)
    print(count(arr, N))
 
# This code is contributed by rakeshsahni


C#




// C# program to find Count the pair of
// elements in  an array such that
// arr[i]+i=arr[j]+j
using System;
class GFG {
 
    // Function to return the
    // total count of pairs
    static int count(int[] arr, int n)
    {
        int ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if ((arr[i] + i) == (arr[j] + j)) {
                    ans++;
                }
            }
        }
        return ans;
    }
 
    // Driver code
    public static int Main()
    {
        int[] arr = new int[] { 6, 1, 4, 3 };
        int N = arr.Length;
        Console.WriteLine(count(arr, N));
        return 0;
    }
}
 
// This code is contributed by Taranpreet


Javascript




<script>
// Javascript program to find Count the pair of
// elements in  an array such that
// arr[i]+i=arr[j]+j
 
// Function to return the
// total count of pairs
function count(arr, n)
{
    let ans = 0;
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {
            if ((arr[i] + i) == (arr[j] + j)) {
                ans++;
            }
        }
    }
    return ans;
}
 
// Driver code
let arr = [ 6, 1, 4, 3 ];
let N = arr.length;
document.write(count(arr, N));
 
// This code is contributed by Samim Hossain Mondal.
</script>


 
 

Output

3

 

Time complexity: O(N^2)
Auxiliary Space: O(1)

 

Efficient Approach: This problem can be efficiently solved by using unordered_map in C++. This is done to store the similar elements count in an average time of O(1). Then for each similar element, we can use the count of that element to evaluate the total number of pairs, as 

 

For x similar items => number of pairs will be x*(x-1)/2

 

Below is the implementation of the above approach:

 

C++




// C++ program to find Count the pair of
// elements in  an array such that
// arr[i]+i=arr[j]+j
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the
// total count of pairs
int count(int arr[], int n)
{
    // Modifying the array by storing
    // a[i]+i at all instances
    for (int i = 0; i < n; i++) {
        arr[i] = arr[i] + i;
    }
 
    // Using unordered_map to store
    // the elements
    unordered_map<int, int> mp;
 
    for (int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }
 
    // Now for each elements in unordered_map
    // we are using the count of that element
    // to determine the number of pairs possible
    int ans = 0;
    for (auto it = mp.begin(); it != mp.end(); it++) {
        int val = it->second;
        ans += (val * (val - 1)) / 2;
    }
    return ans;
}
 
// Driver code
int main()
{
    int arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << count(arr, N);
    return 0;
}


Java




/*package whatever //do not write package name here */
 
// Java program to find Count the pair of
// elements in an array such that
// arr[i]+i=arr[j]+j
import java.io.*;
import java.util.*;
 
class GFG {
 
// Function to return the
// total count of pairs
static int count(int arr[], int n)
{
   
    // Modifying the array by storing
    // a[i]+i at all instances
    for (int i = 0; i < n; i++) {
        arr[i] = arr[i] + i;
    }
 
    // Using unordered_map to store
    // the elements
    HashMap<Integer,Integer>mp = new HashMap<Integer,Integer>();
 
    for (int i = 0; i < n; i++) {
        if(mp.containsKey(arr[i])){
            mp.put(arr[i], mp.get(arr[i])+1);
        }
        else mp.put(arr[i],1);
    }
 
    // Now for each elements in unordered_map
    // we are using the count of that element
    // to determine the number of pairs possible
    int ans = 0;
    for(int it : mp.keySet()){
        ans += (mp.get(it)*(mp.get(it)-1))/2;
    }
    return ans;
}
 
// Driver code
public static void main(String args[])
{
    int arr[] = { 8, 7, 6, 5, 4, 3, 2, 1 };
    int N = arr.length;
    System.out.println(count(arr, N));
}
}
 
// This code is contributed by shinjanpatra


Python3




# Python program to find Count the pair of
# elements in  an array such that
# arr[i]+i=arr[j]+j
 
 
# Function to return the
# total count of pairs
def count(arr, n):
 
    # Modifying the array by storing
    # a[i]+i at all instances
    for i in range(n):
        arr[i] = arr[i] + i
 
    # Using unordered_map to store
    # the elements
    mp = {}
 
    for i in range(n):
        if(arr[i] in mp):
            mp[arr[i]] = mp[arr[i]]+1
        else:
            mp[arr[i]] = 1
 
    # Now for each elements in unordered_map
    # we are using the count of that element
    # to determine the number of pairs possible
    ans = 0
    for val in mp.values():
        ans += (val * (val - 1)) // 2
     
    return ans
 
# Driver code
 
arr = [ 8, 7, 6, 5, 4, 3, 2, 1 ]
N = len(arr)
print(count(arr, N))
 
# This code is contributed by shinjanpatra


Javascript




<script>
 
// JavaScript program to find Count the pair of
// elements in  an array such that
// arr[i]+i=arr[j]+j
 
// Function to return the
// total count of pairs
function count(arr, n)
{
 
    // Modifying the array by storing
    // a[i]+i at all instances
    for (let i = 0; i < n; i++) {
        arr[i] = arr[i] + i;
    }
 
    // Using unordered_map to store
    // the elements
    let mp = new Map();
 
    for (let i = 0; i < n; i++) {
        if(mp.has(arr[i])){
            mp.set(arr[i], mp.get(arr[i]) + 1);
        }
        else mp.set(arr[i], 1);
    }
 
    // Now for each elements in unordered_map
    // we are using the count of that element
    // to determine the number of pairs possible
    let ans = 0;
    for (let [key,val] of mp){
        ans += Math.floor((val * (val - 1)) / 2);
    }
    return ans;
}
 
// Driver code
let arr = [ 8, 7, 6, 5, 4, 3, 2, 1 ];
let N = arr.length;
document.write(count(arr, N));
 
// This code is contributed by shinjanpatra
 
</script>


Output

28

Time complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!