Count of index pairs with equal elements in an array | Set 2 | Java program for the above approach ; Function that counts the pair in the array arr [ ] ; Sort the array ; Initialize two pointers ; Add all valid pairs to answer ; Return the answer ; Driver Code ; Given array arr [ ] ; Function call
import java . util . * ; class GFG { static int countPairs ( int arr [ ] , int n ) { int ans = 0 ; Arrays . sort ( arr ) ; int left = 0 , right = 1 ; while ( right < n ) { if ( arr [ left ] == arr [ right ] ) ans += right - left ; else left = right ; right ++ ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 2 , 3 , 2 , 3 } ; int N = arr . length ; System . out . print ( countPairs ( arr , N ) ) ; } }