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 ; Driven Code
def sumoflength ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE j = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( j < n and ( arr [ j ] not in s ) ) : NEW_LINE INDENT s . append ( arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT ans += ( ( j - i ) * ( j - i + 1 ) ) // 2 NEW_LINE s . remove ( arr [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumoflength ( arr , n ) ) NEW_LINE DEDENT