Sum of Unique Elements — Solution in Python, Java & C++
Sum of Unique Elements solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Sum of Unique Elements is an easy coding problem on arrays, hash table and counting, asked in Amazon and Infosys interviews.
- Difficulty: Easy
- Topics: Arrays, Hash Table, Counting
- Asked at: Amazon, Infosys
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
An element is unique if it appears exactly once in the array.
Given an integer array nums, return the sum of all its unique elements.
Example 1
Input: nums = [1,2,3,2]
Output: 4
Explanation: 1 and 3 are unique; 2 appears twice.
Example 2
Input: nums = [1,1,1,1,1]
Output: 0
Example 3
Input: nums = [1,2,3,4,5]
Output: 15
Constraints
1 <= nums.length <= 1001 <= nums[i] <= 100
Hints for Sum of Unique Elements
Hint 1
Count first, then sum only the values whose count is 1.
Hint 2
Values are bounded by 100, so a fixed-size counting array works.
Hint 3
An array of all duplicates sums to 0.
How to solve Sum of Unique Elements
Uniqueness is a property of the frequency table, so count first and then filter.
Approach
- Tally how many times each value appears.
- Sum the distinct values whose tally is exactly 1.
Why it works
The condition depends only on each value's total count, which the tally captures exactly.
Complexity
- Time —
O(n) - Space —
O(V)
Pitfalls
- Summing the array and subtracting duplicates is fiddly — a duplicated value must be removed entirely, not once.
- Adding the value once per occurrence would double-count if the filter were wrong.
Reference solution
Python
from typing import List
def sumOfUnique(nums: List[int]) -> int:
count = {}
for x in nums:
count[x] = count.get(x, 0) + 1
return sum(v for v, c in count.items() if c == 1)Java
public static int sumOfUnique(int[] nums) {
int[] count = new int[101];
for (int x : nums) count[x]++;
int total = 0;
for (int v = 1; v <= 100; v++) {
if (count[v] == 1) total += v;
}
return total;
}C++
int sumOfUnique(vector<int>& nums) {
vector<int> count(101, 0);
for (int x : nums) count[x]++;
int total = 0;
for (int v = 1; v <= 100; v++) {
if (count[v] == 1) total += v;
}
return total;
}JavaScript
var sumOfUnique = function(nums) {
const count = new Array(101).fill(0);
for (let i = 0; i < nums.length; i++) count[nums[i]]++;
let total = 0;
for (let v = 1; v <= 100; v++) {
if (count[v] === 1) total += v;
}
return total;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Hashing: Hash Maps and Hash Sets