Count unordered pairs of equal elements for all subarrays | Java program for the above approach ; Function to count all pairs ( i , j ) such that arr [ i ] equals arr [ j ] in all possible subarrays of the array ; Stores the size of the array ; Stores the positions of all the distinct elements ; Append index corresponding to arr [ i ] in the map ; Traverse the map M ; Traverse the array ; Update the value of ans ; Update the value of the sum ; Print the value of ans ; Driver Code
import java . io . * ; import java . util . * ; import java . util . List ; import com . google . common . collect . * ; class GFG { static void countPairs ( int [ ] arr ) { int N = arr . length ; int ans = 0 ; ListMultimap < Integer , Integer > M = ArrayListMultimap . create ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { M . put ( arr [ i ] , i ) ; } for ( var it : M . keySet ( ) ) { List < Integer > v = M . get ( it ) ; int sum = 0 ; for ( int j : v ) { ans += sum * ( N - j ) ; sum += j + 1 ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 1 , 1 } ; countPairs ( arr ) ; } }