Subarrays with 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
function sumoflength ( arr , n ) { let s = new Set ( ) ; let j = 0 , ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { while ( j < n && ! s . has ( arr [ j ] ) ) { s . add ( arr [ i ] ) ; j ++ ; } ans += Math . floor ( ( ( j - i ) * ( j - i + 1 ) ) / 2 ) ; s . delete ( arr [ i ] ) ; } return ans ; } let arr = [ 1 , 2 , 3 , 4 ] ; let n = arr . length ; document . write ( sumoflength ( arr , n ) ) ;