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

Last Updated : 16 Sep, 2026

Given an array arr[]. Find the sum of distinct elements in an array.

Examples: 

Input: arr[] = [1, 2, 3, 4, 5]
Output: 15
Explanation: Distinct elements are 1, 2, 3, 4, 5. So sum is 15.

Input: arr[] = [5, 5, 5, 5, 5]
Output: 5
Explanation: Only Distinct element is 5. So sum is 5.

Try It Yourself
redirect icon

[Naive Approach] Check Previous Elements - O(n ^ 2) Time and O(1) Space

The idea is to check whether each element has already appeared before adding it to the sum. If it has not appeared, consider it distinct.

Working of Approach:

  • Initialize sum as 0.
  • Traverse the array one element at a time.
  • For every element, check all previous elements.
  • If the element is not found earlier, add it to sum.
C++
#include <iostream>
#include <vector>
using namespace std;

int findSum(vector<int> &arr)
{
    int n = arr.size();
    int sum = 0;

    // Traverse each element of the array
    for (int i = 0; i < n; i++)
    {
        bool found = false;

        // Check if the element appeared earlier
        for (int j = 0; j < i; j++)
        {
            if (arr[i] == arr[j])
            {
                found = true;
                break;
            }
        }

        // Add the element if it is distinct
        if (!found)
        {
            sum += arr[i];
        }
    }

    return sum;
}

int main()
{

    vector<int> arr = {5, 5, 5, 5, 5};

    cout << findSum(arr) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    public int findSum(int[] arr)
    {
        int n = arr.length;
        int sum = 0;

        // Traverse each element of the array
        for (int i = 0; i < n; i++) {
            boolean found = false;

            // Check if the element appeared earlier
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    found = true;
                    break;
                }
            }

            // Add the element if it is distinct
            if (!found) {
                sum += arr[i];
            }
        }

        return sum;
    }

    public static void main(String[] args)
    {

        int[] arr = { 5, 5, 5, 5, 5 };

        System.out.println(new GFG().findSum(arr));
    }
}
Python
def findSum(arr):
    n = len(arr)
    sum = 0

    # Traverse each element of the array
    for i in range(n):
        found = False

        # Check if the element appeared earlier
        for j in range(i):
            if arr[i] == arr[j]:
                found = True
                break

        # Add the element if it is distinct
        if not found:
            sum += arr[i]

    return sum

if __name__ == '__main__' :
    arr = [5, 5, 5, 5, 5]
    print(findSum(arr))
C#
using System;

class GFG {
    public int findSum(int[] arr)
    {
        int n = arr.Length;
        int sum = 0;

        // Traverse each element of the array
        for (int i = 0; i < n; i++) {
            bool found = false;

            // Check if the element appeared earlier
            for (int j = 0; j < i; j++) {
                if (arr[i] == arr[j]) {
                    found = true;
                    break;
                }
            }

            // Add the element if it is distinct
            if (!found) {
                sum += arr[i];
            }
        }

        return sum;
    }

    public static void Main()
    {

        int[] arr = { 5, 5, 5, 5, 5 };

        Console.WriteLine(new GFG().findSum(arr));
    }
}
JavaScript
function findSum(arr)
{
    let n = arr.length;
    let sum = 0;

    // Traverse each element of the array
    for (let i = 0; i < n; i++) {
        let found = false;

        // Check if the element appeared earlier
        for (let j = 0; j < i; j++) {
            if (arr[i] === arr[j]) {
                found = true;
                break;
            }
        }

        // Add the element if it is distinct
        if (!found) {
            sum += arr[i];
        }
    }

    return sum;
}

// Driver Code
const arr = [ 5, 5, 5, 5, 5 ];
console.log(findSum(arr));

Output
5

[Better Approach] Using Sorting - O(n log n) Time and O(1) Space

The idea is to first sort the array so that equal elements come together. Then, add an element to the sum only when it is different from the previous element.

Working of Approach:

  • Sort the array in ascending order.
  • Initialize sum with the first element.
  • Traverse the sorted array from the second element.
  • If the current element is different from the previous element, add it to sum.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int findSum(vector<int> &arr)
{
    int n = arr.size();
    int sum = 0;

    // Sort the array in ascending order
    sort(arr.begin(), arr.end());

    // Add the first element
    sum = arr[0];

    // Traverse the sorted array
    for (int i = 1; i < n; i++)
    {

        // Add the element if it is different from the previous one
        if (arr[i] != arr[i - 1])
        {
            sum += arr[i];
        }
    }

    return sum;
}

int main()
{

    vector<int> arr = {5, 5, 5, 5, 5};

    cout << findSum(arr) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    public int findSum(int[] arr)
    {
        int n = arr.length;
        int sum = 0;

        // Sort the array in ascending order
        Arrays.sort(arr);

        // Add the first element
        sum = arr[0];

        // Traverse the sorted array
        for (int i = 1; i < n; i++) {

            // Add the element if it is different from the
            // previous one
            if (arr[i] != arr[i - 1]) {
                sum += arr[i];
            }
        }

        return sum;
    }

    public static void main(String[] args)
    {

        int[] arr = { 5, 5, 5, 5, 5 };

        System.out.println(new GFG().findSum(arr));
    }
}
Python
def findSum(arr):
    n = len(arr)
    sum = 0

    # Sort the array in ascending order
    arr.sort()

    # Add the first element
    sum = arr[0]

    # Traverse the sorted array
    for i in range(1, n):

        # Add the element if it is different from the previous one
        if arr[i]!= arr[i - 1]:
            sum += arr[i]

    return sum

if __name__ == '__main__':
    arr = [5, 5, 5, 5, 5]
    print(findSum(arr))
C#
using System;

class GFG {
    public int findSum(int[] arr)
    {
        int n = arr.Length;
        int sum = 0;

        // Sort the array in ascending order
        Array.Sort(arr);

        // Add the first element
        sum = arr[0];

        // Traverse the sorted array
        for (int i = 1; i < n; i++) {

            // Add the element if it is different from the
            // previous one
            if (arr[i] != arr[i - 1]) {
                sum += arr[i];
            }
        }

        return sum;
    }

    public static void Main()
    {

        int[] arr = { 5, 5, 5, 5, 5 };

        Console.WriteLine(new GFG().findSum(arr));
    }
}
JavaScript
function findSum(arr)
{
    let n = arr.length;
    let sum = 0;

    // Sort the array in ascending order
    arr.sort((a, b) => a - b);

    // Add the first element
    sum = arr[0];

    // Traverse the sorted array
    for (let i = 1; i < n; i++) {

        // Add the element if it is different from the
        // previous one
        if (arr[i] !== arr[i - 1]) {
            sum += arr[i];
        }
    }

    return sum;
}

// Driver Code
let arr = [ 5, 5, 5, 5, 5 ];
console.log(findSum(arr));

Output
5

[Expected Approach] Using Hash Set - O(n) Time and O(n) Space

The idea is to use a hash set to keep track of elements already seen. Add an element to the sum only when it appears for the first time.

Working of Approach:

  • Initialize sum as 0 and create an unordered_set.
  • Traverse all elements of the array.
  • Check whether the current element is already present in the set.
  • If it is not present, add it to sum and insert it into the set.

Let us understand with an example:
Input: arr[] = [5, 5, 5, 5, 5]

  • Initially, sum = 0 and the hash set s is empty.
  • For the first 5, it is not present in s, so add 5 to sum and insert it into s.
  • For every remaining 5, it is already present in s, so it is not added again.
  • Thus, only the distinct element 5 contributes to the sum.
  • Finally, sum = 5, so the output is 5.
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;

int findSum(vector<int> &arr)
{
    int n = arr.size();
    int sum = 0;

    // Hash to store all elements of the array
    unordered_set<int> s;

    // Traverse the array
    for (int i = 0; i < n; i++)
    {

        // Check if the element is not already present
        if (s.find(arr[i]) == s.end())
        {
            sum += arr[i];
            s.insert(arr[i]);
        }
    }

    return sum;
}

int main()
{

    vector<int> arr = {5, 5, 5, 5, 5};

    cout << findSum(arr) << endl;

    return 0;
}
Java
import java.util.*;

class GFG {
    public int findSum(int[] arr)
    {
        int n = arr.length;
        int sum = 0;

        // Hash to store all elements of the array
        HashSet<Integer> s = new HashSet<>();

        // Traverse the array
        for (int i = 0; i < n; i++) {

            // Check if the element is not already present
            if (!s.contains(arr[i])) {
                sum += arr[i];
                s.add(arr[i]);
            }
        }

        return sum;
    }

    public static void main(String[] args)
    {

        int[] arr = { 5, 5, 5, 5, 5 };

        System.out.println(new GFG().findSum(arr));
    }
}
Python
def findSum(arr):
    n = len(arr)
    sum = 0

    # Hash to store all elements of the array
    s = set()

    # Traverse the array
    for i in range(n):
        
        # Check if the element is not already present
        if arr[i] not in s:
            sum += arr[i]
            s.add(arr[i])

    return sum

if __name__ == '__main__' :
    arr = [5, 5, 5, 5, 5]
    print(findSum(arr))
C#
using System;
using System.Collections.Generic;

class GFG {
    public int findSum(int[] arr)
    {
        int n = arr.Length;
        int sum = 0;

        // Hash to store all elements of the array
        HashSet<int> s = new HashSet<int>();

        // Traverse the array
        for (int i = 0; i < n; i++) {

            // Check if the element is not already present
            if (!s.Contains(arr[i])) {
                sum += arr[i];
                s.Add(arr[i]);
            }
        }

        return sum;
    }

    public static void Main()
    {

        int[] arr = { 5, 5, 5, 5, 5 };

        Console.WriteLine(new GFG().findSum(arr));
    }
}
JavaScript
function findSum(arr)
{
    let n = arr.length;
    let sum = 0;

    // Hash to store all elements of the array
    let s = new Set();

    // Traverse the array
    for (let i = 0; i < n; i++) {

        // Check if the element is not already present
        if (!s.has(arr[i])) {
            sum += arr[i];
            s.add(arr[i]);
        }
    }

    return sum;
}

// Driver Code
let arr = [ 5, 5, 5, 5, 5 ];

console.log(findSum(arr));

Output
5
Comment