Count of subarrays which start and end with the same element | Java program to Count total sub - array which start and end with same element ; function to find total sub - array which start and end with same element ; initialize result with 0 ; array to count frequency of 1 to N ; update frequency of A [ i ] ; update result with sub - array contributed by number i ; print the result ; Driver code
public class Main { public static void cntArray ( int A [ ] , int N ) { int result = 0 ; int [ ] frequency = new int [ N + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { frequency [ A [ i ] ] ++ ; } for ( int i = 1 ; i <= N ; i ++ ) { int frequency_of_i = frequency [ i ] ; result += ( ( frequency_of_i ) * ( frequency_of_i + 1 ) ) / 2 ; } System . out . println ( result ) ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 5 , 6 , 1 , 9 , 5 , 8 , 10 , 8 , 9 } ; int N = A . length ; cntArray ( A , N ) ; } }