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

Last Updated : 12 Dec, 2022

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 ` `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

 ``

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 ` `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 mp` `            ``= ``new` `HashMap();` `      `  `          ``// 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 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

 ``

Output:

`15`

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