Count the pairs in an array such that the difference between them and their indices is equal | C ++ implementation of the approach ; Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { unordered_map < int , int > map ; for ( int i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] ++ ; int res = 0 ; for ( auto x : map ) { int cnt = x . second ; res += ( ( cnt * ( cnt - 1 ) ) / 2 ) ; } return res ; } int main ( ) { int arr [ ] = { 1 , 5 , 6 , 7 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }