Suppose we have an array nums with few duplicate elements and some unique elements. We have to find the sum of all the unique elements present in nums.
So, if the input is like nums = [5,2,1,5,3,1,3,8], then the output will be 10 because only unique elements are 8 and 2, so their sum is 10.
To solve this, we will follow these steps −
count := a dictionary holding all unique elements and their frequency
ans := 0
for each index i and value v in nums, do
if count[v] is same as 1, then
ans := ans + v
return ans
Example (Python)
Let us see the following implementation to get better understanding −
from collections import Counter def solve(nums): count = Counter(nums) ans = 0 for index,value in enumerate(nums): if count[value]==1: ans+=value return ans nums = [5,2,1,5,3,1,3,8] print(solve(nums))
Input
[5,2,1,5,3,1,3,8]
Output
10