Open In App

Count pairs of indices having sum of indices same as the sum of elements at those indices

Last Updated : 12 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] consisting of N integers, the task is to find the number of pairs (i, j) whose sum of indices is the same as the sum elements at the indices.

Examples:

Input: arr[] = {0, 1, 7, 4, 3, 2}
Output: 1
Explanation: There exists only pair that satisfies the condition is {(0, 1)}.

Input: arr[] = {1, 6, 2, 4, 5, 6}
Output: 0

Naive Approach: The simple approach to solve the given problem is to generate all possible pairs of the given array and if the sum of any pairs is the same as the sum of its indices, then count this pair. After checking for all the pairs, print the total count obtained.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
void countPairs(int arr[], int N)
{
    // Stores the total count of pairs
    int answer = 0;
 
    // Iterate over the range
    for (int i = 0; i < N; i++) {
 
        // Iterate over the range
        for (int j = i + 1; j < N; j++) {
            if (arr[i] + arr[j] == i + j) {
                answer++;
            }
        }
    }
 
    // Print the total count
    cout << answer;
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countPairs(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
public class GFG{
 
// Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
public static void countPairs(int arr[], int N)
{
     
    // Stores the total count of pairs
    int answer = 0;
 
    // Iterate over the range
    for(int i = 0; i < N; i++)
    {
         
        // Iterate over the range
        for(int j = i + 1; j < N; j++)
        {
            if (arr[i] + arr[j] == i + j)
            {
                answer++;
            }
        }
    }
     
    // Print the total count
    System.out.println(answer);
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 0, 1, 2, 3, 4, 5 };
    int N = arr.length;
 
    countPairs(arr, N);
}
}
 
// This code is contributed by gfgking


Python3




# Python3 program for the above approach
 
# Function to find all possible pairs
# of the given array such that the sum
# of arr[i] + arr[j] is i + j
def countPairs(arr, N):
     
    # Stores the total count of pairs
    answer = 0
     
    # Iterate over the range
    for i in range(N):
         
        # Iterate over the range
        for j in range(i + 1, N):
            if arr[i] + arr[j] == i + j:
                answer += 1
                 
    # Print the total count            
    print(answer)
 
# Driver code
arr = [ 0, 1, 2, 3, 4, 5 ]
N = len(arr)
 
countPairs(arr, N)
 
# This code is contributed by Parth Manchanda


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
static void countPairs(int[] arr, int N)
{
     
    // Stores the total count of pairs
    int answer = 0;
 
    // Iterate over the range
    for(int i = 0; i < N; i++)
    {
         
        // Iterate over the range
        for(int j = i + 1; j < N; j++)
        {
            if (arr[i] + arr[j] == i + j)
            {
                answer++;
            }
        }
    }
 
    // Print the total count
    Console.Write(answer);
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = { 0, 1, 2, 3, 4, 5 };
    int N = arr.Length;
     
    countPairs(arr, N);
}
}
 
// This code is contributed by target_2


Javascript




<script>
 
        // JavaScript program for the above approach
 
        // Function to find all possible pairs
        // of the given array such that the sum
        // of arr[i] + arr[j] is i + j
        function countPairs(arr, N)
        {
         
            // Stores the total count of pairs
            let answer = 0;
 
            // Iterate over the range
            for (let i = 0; i < N; i++) {
 
                // Iterate over the range
                for (let j = i + 1; j < N; j++) {
                    if (arr[i] + arr[j] == i + j) {
                        answer++;
                    }
                }
            }
 
            // Print the total count
            document.write(answer);
        }
 
        // Driver Code
        let arr = [0, 1, 2, 3, 4, 5];
        let N = arr.length;
 
        countPairs(arr, N);
         
// This code is contributed by Potta Lokesh
    </script>


Output: 

15

 

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can also be optimized by using an unordered map to store the count of elements having (arr[i] – i) value in the array arr[]. Follow the steps below to solve the problem:

  • Initialize the variable, say answer as 0 to store the count of pairs in the array arr[].
  • Initialize an unordered map mp[] to store the frequency of an element in the array arr[] having value (arr[i] – i).
  • Iterate over the range [0, N] using the variable i and perform the following steps:
    • Initialize the variable keyValue as the value of (arr[i] – i).
    • Increase the value of keyValue in the unordered map mp[] by 1.
  • Iterate over the unordered map mp[] using the variable i and perform the following steps:
    • Initialize the variable size as i.second the value of the unordered map mp[].
    • Add the value of size*(size – 1)/2 to the variable answer.
  • After performing the above steps, print the value of the answer as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
void countPairs(int arr[], int N)
{
    // Stores the total count of pairs
    int answer = 0;
 
    unordered_map<int, int> mp;
 
    // Iterate over the range [0, N]
    for (int i = 0; i < N; i++) {
        int keyValue = arr[i] - i;
        mp[keyValue]++;
    }
 
    // Iterate over the range [0, N]
    for (auto i : mp) {
        int size = i.second;
        answer += (size * (size - 1)) / 2;
    }
 
    // Print the answer
    cout << answer;
}
 
// Driver Code
int main()
{
    int arr[] = { 0, 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    countPairs(arr, N);
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
   
  // Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
    public static void countPairs(int[] arr, int n)
    {
       
          // Stores the total count of pairs
        int answer = 0;
        HashMap<Integer, Integer> mp
            = new HashMap<Integer, Integer>();
       
          // Iterate over the range [0, N]
        for (int i = 0; i < n; i++) {
            int value = arr[i] - i;
            if (mp.containsKey(value)) {
                mp.put(value, mp.get(value) + 1);
            }
            else {
                mp.put(value, 1);
            }
        }
       
          // Iterate over the range [0, N]
        for (Map.Entry<Integer, Integer> map :
             mp.entrySet()) {
            int temp = map.getValue();
            answer += temp * (temp - 1) / 2;
        }
       
          // Print the answer
        System.out.println(answer);
    }
   
  // Driver code
    public static void main(String[] args)
    {
        int[] arr = { 0, 1, 2, 3, 4, 5 };
        int n = 6;
        countPairs(arr, n);
    }
}
 
// This code is contributed by maddler.


Python3




# Python3 program for the above approach
 
# Function to find all possible pairs
# of the given array such that the sum
# of arr[i] + arr[j] is i + j
def countPairs(arr, N):
     
    # Stores the total count of pairs
    answer = 0
    mp = {}
     
    # Iterate over the range [0, N]
    for i in range(N):
        keyValue = arr[i] - i
        if keyValue in mp.keys():
            mp[keyValue] += 1
        else:
            mp[keyValue] = 1
             
    # Iterate over the range [0, N]
    for size in mp.values():
        answer += (size * (size - 1)) // 2
         
    print(answer)
 
# Driver code
arr = [ 0, 1, 2, 3, 4, 5 ]
N = len(arr)
 
countPairs(arr, N)
 
# This code is contributed by Parth Manchanda


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
static void countPairs(int []arr, int N)
{
    // Stores the total count of pairs
    int answer = 0;
     
    Dictionary<int,int> mp = new Dictionary<int,int>();
 
    // Iterate over the range [0, N]
    for (int i = 0; i < N; i++) {
        int keyValue = arr[i] - i;
        if(mp.ContainsKey(keyValue))
          mp[keyValue]++;
        else
          mp.Add(keyValue,1);
    }
 
    // Iterate over the range [0, N]
    foreach(KeyValuePair<int,int> entry in mp)
    {
        int size = entry.Value;
        answer += (size * (size - 1)) / 2;
    }
 
    // Print the answer
    Console.Write(answer);
}
 
// Driver Code
public static void Main()
{
    int []arr = {0, 1, 2, 3, 4, 5 };
    int N = arr.Length;
    countPairs(arr, N);
}
}
 
// This code is contributed by SURENDRA_GANGWAR.


Javascript




<script>
// Javascript program for the above approach
 
// Function to find all possible pairs
// of the given array such that the sum
// of arr[i] + arr[j] is i + j
function countPairs(arr, N) {
  // Stores the total count of pairs
  let answer = 0;
 
  let mp = new Map();
 
  // Iterate over the range [0, N]
  for (let i = 0; i < N; i++) {
    let keyValue = arr[i] - i;
 
    if (mp.has(keyValue)) {
      mp.set(keyValue, mp.get(keyValue) + 1);
    } else {
      mp.set(keyValue, 1);
    }
  }
 
  // Iterate over the range [0, N]
  for (let i of mp) {
    let size = i[1];
    answer += (size * (size - 1)) / 2;
  }
 
  // Print the answer
  document.write(answer);
}
 
// Driver Code
 
let arr = [0, 1, 2, 3, 4, 5];
let N = arr.length;
 
countPairs(arr, N);
 
// This code is contributed by _saurabh_jaiswal.
</script>


Output: 

15

 

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



Similar Reads

Count pairs with product of indices equal to the product of elements present at those indices
Given an array arr[] consisting of N integers, the task is to count the number of distinct pairs of array elements having the product of indices equals the product of elements at that indices. The pairs (x, y) and (y, x) are considered as the same pairs. Examples: Input: arr[] = {1, 0, 3, 2, 6}Output: 3Explanation: All possible pairs satisfying the
5 min read
Count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices
Given an array arr[] of N integers, the task is to find the number of unordered pairs (i, j) in the array such that the ratio of elements at these indices is the same as the ratio of indices (arr[j]/arr[i] = j/i). Examples: Input: arr[] = {4, 5, 12, 10, 6}Output: 2Explanation: The pairs that follow the given condition are: (1, 3) as arr[3] / arr[1]
10 min read
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices
Given an array arr[] consisting of N positive integers, the task is to find the number of pairs (i, j) such that i &lt; j and the product of elements at these indices is equal to the absolute difference of their indices. Examples: Input: arr[] = {1, 1, 2, 4}Output: 2Explanation:Following are the possible pairs: (0, 1): The sum of these indices is 0
10 min read
Count of maximum occurring subsequence using only those characters whose indices are in GP
Given a string S, the task is to find the count of maximum occurring subsequence P from S using only those characters whose indexes are in Geometric Progression.Note: Consider 1-based indexing in S. Examples : Input: S = "ddee"Output: 4Explanation: If we take P = "de", then P occurs 4 times in S. { {1, 3}, {1, 4}, {2, 3}, {2, 4} } Input: S = "geeks
7 min read
Find the Array Permutation having sum of elements at odd indices greater than sum of elements at even indices
Given an array arr[] consisting of N integers, the task is to find the permutation of array elements such that the sum of odd indices elements is greater than or equal to the sum of even indices elements. Examples: Input: arr[] = {1, 2, 3, 4}Output: 1 4 2 3 Explanation:Consider the permutation of the given array as {1, 4, 2, 3}.Now, the sum of elem
6 min read
Count pairs of same parity indexed elements with same MSD after replacing each element by the sum of maximum digit * A and minimum digits * B
Given an array arr[] of N 3-digit integers and two integers a and b, the task is to modify each array element according to the following rules: Find the maximum, say M, and minimum digit, say m, of each array element arr[i].Update the array element arr[i] as (A * M + B * m). The task is to count the number of pairs such that the chosen elements are
12 min read
Count elements of same value placed at same indices of two given arrays
Given two arrays A[] and B[] of N unique elements, the task is to find the maximum number of matched elements from the two given arrays. Elements of the two arrays are matched if they are of the same value and can be placed at the same index (0-based indexing).(By right shift or left shift of the two arrays). Examples: Input: A[] = { 5, 3, 7, 9, 8
8 min read
Count distinct pairs from two arrays having same sum of digits
Given two arrays arr1[] and arr2[]. The task is to find the total number of distinct pairs(formed by picking 1 element from arr1 and one element from arr2), such that both the elements of the pair have the sum of digits. Note: Pairs occurring more than once must be counted only once. Examples: Input : arr1[] = {33, 41, 59, 1, 3} arr2[] = {3, 32, 51
7 min read
Maximize sum of paths from LCA of nodes u and v to one of those nodes
Given a tree consisting of N nodes an array edges[][3] of size N - 1 such that for each {X, Y, W} in edges[] there exists an edge between node X and node Y with a weight of W and two nodes u and v, the task is to find the maximum sum of weights of edges in the path from Lowest Common Ancestor(LCA) of nodes (u, v) to node u and node v. Examples: Inp
14 min read
Split the integer in two parts such that the difference between the digit sum of those values is not more than 1
Given an integer val. Split the given integer in two integers val1 and val2 such that val1 + val2 = val and the difference between the digit sum of val1 and val2 is not more than 1, the task is to print val1 and val2. (If there are multiple answers, then print any) Examples: Input: val = 161Output: 130 and 31Explanation: The digit sum of 130 is = 4
14 min read
Article Tags :
Practice Tags :