Subarrays with distinct elements | C # program to calculate sum of lengths of subarrays of distinct elements ; Returns sum of lengths of all subarrays with distinct elements . ; For maintaining distinct elements . ; Initialize ending point and result ; Fix starting point ; Calculating and adding all possible length subarrays in arr [ i . . j ] ; Remove arr [ i ] as we pick new stating point from next ; Driver Code
using System ; using System . Collections . Generic ; public class geeks { public static int sumoflength ( int [ ] arr , int n ) { HashSet < int > s = new HashSet < int > ( ) ; int j = 0 , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { while ( j < n && ! s . Contains ( arr [ j ] ) ) { s . Add ( arr [ i ] ) ; j ++ ; } ans += ( ( j - i ) * ( j - i + 1 ) ) / 2 ; s . Remove ( arr [ i ] ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 } ; int n = arr . Length ; Console . WriteLine ( sumoflength ( arr , n ) ) ; } }