![]() |
VOOZH | about |
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:
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:
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:
21
Time Complexity:O(n)
Auxiliary Space: O(n)
Method #3:Using Built-in python and javascript functions:
Approach for python:
Approach for Javascript:
Below is the implementation of the above approach.
21
Time Complexity:O(n)
Auxiliary Space: O(n)