Count pairs ( i , j ) from an array such that i < j and arr [ j ] | Java program for the above approach ; Function to count the number of pairs ( i , j ) such that i < j and arr [ i ] - arr [ j ] = X * ( j - i ) ; Stores the count of all such pairs that satisfies the condition . ; Stores count of distinct values of arr [ i ] - x * i ; Iterate over the Map ; Increase count of pairs ; Print the count of such pairs ; Driver Code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void countPairs ( int arr [ ] , int n , int x ) { int count = 0 ; HashMap < Integer , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { mp . put ( arr [ i ] - x * i , mp . getOrDefault ( arr [ i ] - x * i , 0 ) + 1 ) ; } for ( int v : mp . values ( ) ) { count += ( v * ( v - 1 ) ) / 2 ; } System . out . println ( count ) ; } public static void main ( String [ ] args ) { int n = 6 , x = 3 ; int arr [ ] = { 5 , 4 , 8 , 11 , 13 , 16 } ; countPairs ( arr , n , x ) ; } }