VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-sum-non-repeating-distinct-elements-array/

⇱ Find sum of non-repeating (distinct) elements in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find sum of non-repeating (distinct) elements in an array

Last Updated : 23 Jul, 2025

Given an integer array with repeated elements, the task is to find the sum of all distinct elements in the array.
Examples:

Input : arr[] = {12, 10, 9, 45, 2, 10, 10, 45,10};
Output : 78
Here we take 12, 10, 9, 45, 2 for sum
because it's distinct elements
Input : arr[] = {1, 10, 9, 4, 2, 10, 10, 45 , 4};
Output : 71

Naive Approach:

A Simple Solution is to use two nested loops. The outer loop picks an element one by one starting from the leftmost element. The inner loop checks if the element is present on right side of it. If present, then ignores the element.

Steps that were to follow the above approach:

  • Make a variable sum and initialize it with 0. It is the variable that will contain the final answer
  • Now traverse the input array
  • While traversing the array pick an element and check all elements to its right by running an inner loop.
  • If we get any element with the same value as that element then stop the inner loop
  • If any element exists to the right of that element that has the same value then it is ok else add the value of that element to the sum.

Code to implement the above approach:

Output-

21

Time Complexity :O(n2,because of two nested loop
Auxiliary Space : O(1) , because no extra space has been used

A Better Solution of this problem is that using sorting technique we firstly sort all elements of array in ascending order and find one by one distinct elements in array. 

Implementation:


Output
21

Time Complexity :O(n log n) 
Auxiliary Space : O(1)

An Efficient solution to this problem is that using unordered_set we run a single for loop and in which the value comes the first time it's an add-in sum variable and stored in a hash table that for the next time we do not use this value.

Implementation:


Output
21

Time Complexity:O(n) 
Auxiliary Space: O(n)

Method #3:Using Built-in python and javascript functions:

Approach for python:

  • Calculate the frequencies using Counter() function
  • Convert the frequency keys to the list.
  • Calculate the sum of the list.

Approach for Javascript:

  • The Counter function from the collections module in Python has been replaced with an empty object.
  • The keys() method is used to extract the keys of the object as an array.
  • The reduce() method is used to calculate the sum of the array.

Below is the implementation of the above approach.


Output
21

Time Complexity:O(n)
Auxiliary Space: O(n)

Comment