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
using System ; using System . Collections . Generic ; class GFG { static int countPairs ( int [ ] arr , int n ) { Dictionary < int , int > map = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] ++ ; int res = 0 ; foreach ( KeyValuePair < int , int > x in map ) { int cnt = x . Value ; res += ( ( cnt * ( cnt - 1 ) ) / 2 ) ; } return res ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 5 , 6 , 7 , 9 } ; int n = arr . Length ; Console . WriteLine ( countPairs ( arr , n ) ) ; } }