Count the pairs in an array such that the difference between them and their indices is equal | Java 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
import java . util . HashMap ; class GFG { static int countPairs ( int arr [ ] , int n ) { HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) map . put ( arr [ i ] - i , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) map . put ( arr [ i ] - i , map . get ( arr [ i ] - i ) + 1 ) ; int res = 0 ; for ( int x : map . values ( ) ) { int cnt = x ; res += ( ( cnt * ( cnt - 1 ) ) / 2 ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 6 , 7 , 9 } ; int n = arr . length ; System . out . println ( countPairs ( arr , n ) ) ; } }