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:
C++
// C++ Find the sum of all non-repeated
// elements in an array
#include<bits/stdc++.h>
using namespace std;
// Find the sum of all non-repeated elements
// in an array
int findSum(int arr[], int n)
{
//Intialized a variable with 0 to contain final answer
int sum = 0;
//Traverse the input array
for (int i=0; i<n; i++)
{
int j=i+1;
while(j<n){
//if any element present on the right of arr[i] that has
//same value as arr[i] then break the loop
if(arr[j]==arr[i]){break;}
j++;
}
//If no such element exists then add this element's value into sum
if(j==n){sum+=arr[i];}
}
//Finally return the answer
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Find the sum of all non-repeated elements
// in an array
public static int findSum(int arr[], int n)
{
// Intialize a variable with 0 to contain final answer
int sum = 0;
// Traverse the input array
for (int i = 0; i < n; i++) {
int j = i + 1;
while (j < n)
{
// If any element present on the right of arr[i] that has
// same value as arr[i], then break the loop
if (arr[j] == arr[i]) {
break;
}
j++;
}
// If no such element exists then add this element's value into sum
if (j == n) {
sum += arr[i];
}
}
// Finally return the answer
return sum;
}
// Driver code
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = arr.length;
System.out.println(findSum(arr, n));
}
}
Python3
# Find the sum of all non-repeated elements
# in an array
def findSum(arr):
# Initialize a variable with 0 to contain final answer
sum = 0
# Traverse the input array
for i in range(len(arr)):
j = i + 1
while j < len(arr):
# If any element present on the right of arr[i] that has
# same value as arr[i] then break the loop
if arr[j] == arr[i]:
break
j += 1
# If no such element exists then add this element's value into sum
if j == len(arr):
sum += arr[i]
# Finally return the answer
return sum
# Driver code
arr = [1, 2, 3, 1, 1, 4, 5, 6]
print(findSum(arr))
C#
// C# code to find the sum of all non-repeated
// elements in an array
using System;
public class GFG {
// Find the sum of all non-repeated elements
// in an array
public static int FindSum(int[] arr, int n)
{
// Initialized a variable with 0 to contain final
// answer
int sum = 0;
// Traverse the input array
for (int i = 0; i < n; i++) {
int j = i + 1;
while (j < n) {
// if any element present on the right of
// arr[i] that has same value as arr[i] then
// break the loop
if (arr[j] == arr[i]) {
break;
}
j++;
}
// If no such element exists then add this
// element's value into sum
if (j == n) {
sum += arr[i];
}
}
// Finally return the answer
return sum;
}
// Driver code
public static void Main() {
int[] arr = { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = arr.Length;
Console.WriteLine(FindSum(arr, n));
}
}
JavaScript
// JavaScript Find the sum of all non-repeated
// elements in an array
// Find the sum of all non-repeated elements
// in an array
function findSum(arr) {
// Intialize a variable with 0 to contain final answer
let sum = 0;
// Traverse the input array
for (let i=0; i<arr.length; i++) {
let j=i+1;
while(j<arr.length){
// If any element present on the right of arr[i] that has
// same value as arr[i] then break the loop
if(arr[j]==arr[i]){break;}
j++;
}
// If no such element exists then add this element's value into sum
if(j==arr.length){sum+=arr[i];}
}
// Finally return the answer
return sum;
}
// Driver code
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
console.log(findSum(arr));
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:
C++
// C++ Find the sum of all non-repeated
// elements in an array
#include<bits/stdc++.h>
using namespace std;
// Find the sum of all non-repeated elements
// in an array
int findSum(int arr[], int n)
{
// sort all elements of array
sort(arr, arr + n);
int sum = 0;
for (int i=0; i<n; i++)
{
if (arr[i] != arr[i+1])
sum = sum + arr[i];
}
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Java
import java.util.Arrays;
// Java Find the sum of all non-repeated
// elements in an array
public class GFG {
// Find the sum of all non-repeated elements
// in an array
static int findSum(int arr[], int n) {
// sort all elements of array
Arrays.sort(arr);
int sum = arr[0];
for (int i = 0; i < n-1; i++) {
if (arr[i] != arr[i + 1]) {
sum = sum + arr[i+1];
}
}
return sum;
}
// Driver code
public static void main(String[] args) {
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.length;
System.out.println(findSum(arr, n));
}
}
Python3
# Python3 Find the sum of all non-repeated
# elements in an array
# Find the sum of all non-repeated elements
# in an array
def findSum(arr, n):
# sort all elements of array
arr.sort()
sum = arr[0]
for i in range(0,n-1):
if (arr[i] != arr[i+1]):
sum = sum + arr[i+1]
return sum
# Driver code
def main():
arr= [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(findSum(arr, n))
if __name__ == '__main__':
main()
# This code is contributed by 29AjayKumar
C#
// C# Find the sum of all non-repeated
// elements in an array
using System;
class GFG
{
// Find the sum of all non-repeated elements
// in an array
static int findSum(int []arr, int n)
{
// sort all elements of array
Array.Sort(arr);
int sum = arr[0];
for (int i = 0; i < n - 1; i++)
{
if (arr[i] != arr[i + 1])
{
sum = sum + arr[i + 1];
}
}
return sum;
}
// Driver code
public static void Main()
{
int []arr = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.Length;
Console.WriteLine(findSum(arr, n));
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// JavaScript Program to find the sum of all non-repeated
// elements in an array
// Find the sum of all non-repeated elements
// in an array
function findSum(arr, n)
{
// sort all elements of array
arr.sort();
let sum = 0;
for (let i=0; i<n; i++)
{
if (arr[i] != arr[i+1])
sum = sum + arr[i];
}
return sum;
}
// Driver code
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
document.write(findSum(arr, n));
// This code is contributed by Surbhi Tyagi
</script>
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:
C++
// C++ Find the sum of all non- repeated
// elements in an array
#include<bits/stdc++.h>
using namespace std;
// Find the sum of all non-repeated elements
// in an array
int findSum(int arr[],int n)
{
int sum = 0;
// Hash to store all element of array
unordered_set< int > s;
for (int i=0; i<n; i++)
{
if (s.find(arr[i]) == s.end())
{
sum += arr[i];
s.insert(arr[i]);
}
}
return sum;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = sizeof(arr)/sizeof(int);
cout << findSum(arr, n);
return 0;
}
Java
// Java Find the sum of all non- repeated
// elements in an array
import java.util.*;
class GFG
{
// Find the sum of all non-repeated elements
// in an array
static int findSum(int arr[], int n)
{
int sum = 0;
// Hash to store all element of array
HashSet<Integer> s = new HashSet<Integer>();
for (int i = 0; i < n; i++)
{
if (!s.contains(arr[i]))
{
sum += arr[i];
s.add(arr[i]);
}
}
return sum;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.length;
System.out.println(findSum(arr, n));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 Find the sum of all
# non- repeated elements in an array
# Find the sum of all non-repeated
# elements in an array
def findSum(arr, n):
s = set()
sum = 0
# Hash to store all element
# of array
for i in range(n):
if arr[i] not in s:
s.add(arr[i])
for i in s:
sum = sum + i
return sum
# Driver code
arr = [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(findSum(arr, n))
# This code is contributed by Shrikant13
C#
// C# Find the sum of all non- repeated
// elements in an array
using System;
using System.Collections.Generic;
class GFG
{
// Find the sum of all non-repeated elements
// in an array
static int findSum(int []arr, int n)
{
int sum = 0;
// Hash to store all element of array
HashSet<int> s = new HashSet<int>();
for (int i = 0; i < n; i++)
{
if (!s.Contains(arr[i]))
{
sum += arr[i];
s.Add(arr[i]);
}
}
return sum;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.Length;
Console.WriteLine(findSum(arr, n));
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program Find the sum of all non- repeated
// elements in an array
// Find the sum of all non-repeated elements
// in an array
function findSum(arr, n)
{
let sum = 0;
// Hash to store all element of array
let s = new Set();
for (let i = 0; i < n; i++)
{
if (!s.has(arr[i]))
{
sum += arr[i];
s.add(arr[i]);
}
}
return sum;
}
// Driver code
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
document.write(findSum(arr, n));
</script>
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.
C++
// c++ program for the above approach
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
// Function to return the sum of distinct elements
int sumOfElements(vector<int> arr, int n) {
// Creating an unordered_map to store the frequency of each element
unordered_map<int, int> freq;
for(int i=0; i<n; i++) {
freq[arr[i]]++;
}
// Creating a vector to store the unique elements
vector<int> lis;
for(auto it=freq.begin(); it!=freq.end(); it++) {
lis.push_back(it->first);
}
// Calculating the sum of unique elements
int sum = 0;
for(int i=0; i<lis.size(); i++) {
sum += lis[i];
}
return sum;
}
// Driver code
int main() {
vector<int> arr = {1, 2, 3, 1, 1, 4, 5, 6};
int n = arr.size();
cout << sumOfElements(arr, n);
return 0;
}
// This code is contributed by Prince Kumar
Java
// Java program for the above approach
import java.util.*;
public class Main {
// Function to return the sum of distinct elements
public static int sumOfElements(List<Integer> arr, int n) {
// Creating a HashMap to store the frequency of each element
HashMap<Integer, Integer> freq = new HashMap<>();
for(int i=0; i<n; i++) {
freq.put(arr.get(i), freq.getOrDefault(arr.get(i), 0) + 1);
}
// Creating a list to store the unique elements
List<Integer> lis = new ArrayList<>();
for(Map.Entry<Integer, Integer> entry : freq.entrySet()) {
lis.add(entry.getKey());
}
// Calculating the sum of unique elements
int sum = 0;
for(int i=0; i<lis.size(); i++) {
sum += lis.get(i);
}
return sum;
}
// Driver code
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(1, 2, 3, 1, 1, 4, 5, 6);
int n = arr.size();
System.out.println(sumOfElements(arr, n));
}
}
// This code is contributed by adityashatmfh
Python3
# Python program for the above approach
from collections import Counter
# Function to return the sum of distinct elements
def sumOfElements(arr, n):
# Counter function is used to
# calculate frequency of elements of array
freq = Counter(arr)
# Converting keys of freq dictionary to list
lis = list(freq.keys())
# Return sum of list
return sum(lis)
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(sumOfElements(arr, n))
# This code is contributed by vikkycirus
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
// Function to return the sum of distinct elements
public static int SumOfElements(List<int> arr, int n)
{
// Creating a Dictionary to store the frequency of each element
Dictionary<int, int> freq = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
if (freq.ContainsKey(arr[i]))
freq[arr[i]]++;
else
freq[arr[i]] = 1;
}
// Creating a list to store the unique elements
List<int> lis = new List<int>();
foreach (KeyValuePair<int, int> entry in freq)
{
lis.Add(entry.Key);
}
// Calculating the sum of unique elements
int sum = 0;
for (int i = 0; i < lis.Count; i++)
{
sum += lis[i];
}
return sum;
}
// Driver code
public static void Main(string[] args)
{
List<int> arr = new List<int> { 1, 2, 3, 1, 1, 4, 5, 6 };
int n = arr.Count;
Console.WriteLine(SumOfElements(arr, n));
}
}
JavaScript
// JavaScript program for the above approach
function sumOfElements(arr, n) {
// Creating an empty object
let freq = {};
// Loop to create frequency object
for(let i = 0; i < n; i++) {
freq[arr[i]] = (freq[arr[i]] || 0) + 1;
}
// Converting keys of freq object to array
let lis = Object.keys(freq).map(Number);
// Return sum of array
return lis.reduce((a, b) => a + b, 0);
}
// Driver code
let arr = [1, 2, 3, 1, 1, 4, 5, 6];
let n = arr.length;
console.log(sumOfElements(arr, n));
Time Complexity: O(n)
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem