Objective: Given an array of integers which contains duplicates as well. Write a program to find the sum of all unique elements in the array. This problem is also referred as find the sum of all distinct elements in the array

Sort the array, this will bring all duplicates together.

Iterate through array and get the sum of all unique elements (If current element which is same as the previous element, ignore the current element).

Time Complexity: O(NlogN)

Use Hash Set–

Create Hash Set and initialize sum = 0.

Iterate through array, check if current element is in Hash Set, if yes then ignore the element else add the element to the sum and add it to the Hash Set.

Time Complexity: O(N), Space Complexity: O(N)

See the code below for both the approaches for better understanding.

Java Code:

Output:

Sum of all Unique elements (Sorting Method): 24
Sum of all Unique elements (HashSet Method: 24

__________________________________________________ Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________