Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of unique elements in Python
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.
Approach
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
Using Counter from Collections
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))
The output of the above code is −
10
Using Dictionary Approach
We can also solve this without using Counter by manually counting frequencies −
def solve(nums):
# Count frequency of each element
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
# Sum elements that appear only once
ans = 0
for num, freq in count.items():
if freq == 1:
ans += num
return ans
nums = [5, 2, 1, 5, 3, 1, 3, 8]
print(solve(nums))
The output of the above code is −
10
Optimized One-Pass Solution
Here's a more efficient approach that processes the array in a single pass −
def solve(nums):
from collections import defaultdict
count = defaultdict(int)
unique_sum = 0
for num in nums:
if count[num] == 0:
# First occurrence - add to sum
unique_sum += num
elif count[num] == 1:
# Second occurrence - remove from sum
unique_sum -= num
# For count > 1, do nothing
count[num] += 1
return unique_sum
nums = [5, 2, 1, 5, 3, 1, 3, 8]
print(solve(nums))
The output of the above code is −
10
Comparison
| Method | Time Complexity | Space Complexity | Passes |
|---|---|---|---|
| Counter Method | O(n) | O(n) | Two |
| Dictionary Method | O(n) | O(n) | Two |
| One-Pass Method | O(n) | O(n) | One |
Conclusion
Use Counter for clean readable code when working with frequency counts. The one-pass solution is most efficient for large datasets as it processes elements in a single iteration.
