Sum of all Unique elements in a given array

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


[] arrA = {1, 6, 4, 3, 2, 2, 3, 8, 1};
Output : 24 
(Unique elements are: 1, 6, 4, 3, 2, 8)

[] arrA = {1, 1, 3, 2, 2, 3};
Output : 6 
(Unique elements are: 1, 2, 3)


Use Sorting-

  • Sort the array, this will bring all duplicates together.
  • Iterate through the array and get the sum of all unique elements (If current element which is the 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 the array, check if the 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:


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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.