Sum of Unique Elements
EasyUpdated: Oct 13, 2025
Practice on:
Problem
You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array.
Return _thesum of all the unique elements of _nums.
Examples
Example 1
Input: nums = [1,2,3,2]
Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.
Example 2
Input: nums = [1,1,1,1,1]
Output: 0
Explanation: There are no unique elements, and the sum is 0.
Example 3
Input: nums = [1,2,3,4,5]
Output: 15
Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.
Constraints
1 <= nums.length <= 1001 <= nums[i] <= 100
Solution
Method 1 - Count Frequency (Counting Array)
Intuition
We count the frequency of each number in nums (using a counting array or hash map) and sum those that appear exactly once into ans.
Approach
We count the frequency of each number into cnt, then sum those indices where cnt[i] == 1 and accumulate into ans.
Code
C++
class Solution {
public:
int sumOfUnique(vector<int>& nums) {
int cnt[101] = {};
for (int x : nums) cnt[x]++;
int ans = 0;
for (int i = 1; i <= 100; ++i) if (cnt[i] == 1) ans += i;
return ans;
}
};
Java
class Solution {
public int sumOfUnique(int[] nums) {
int[] cnt = new int[101];
for (int x : nums) cnt[x]++;
int ans = 0;
for (int i = 1; i <= 100; ++i) if (cnt[i] == 1) ans += i;
return ans;
}
}
Kotlin
class Solution {
fun sumOfUnique(nums: IntArray): Int {
val cnt = IntArray(101)
for (x in nums) cnt[x]++
var ans = 0
for (i in 1..100) if (cnt[i] == 1) ans += i
return ans
}
}
Python
class Solution:
def sumOfUnique(self, nums: list[int]) -> int:
from collections import Counter
return sum(x for x, c in Counter(nums).items() if c == 1)
Rust
use std::collections::HashMap;
impl Solution {
pub fn sum_of_unique(nums: Vec<i32>) -> i32 {
let mut cnt = std::collections::HashMap::new();
for x in nums.iter() { *cnt.entry(x).or_insert(0) += 1; }
cnt.into_iter().filter(|(_,c)| *c == 1).map(|(x,_)| *x).sum()
}
}
TypeScript
function sumOfUnique(nums: number[]): number {
const cnt = new Map<number, number>();
for (const x of nums) cnt.set(x, (cnt.get(x) ?? 0) + 1);
let ans = 0;
for (const [x, c] of cnt.entries()) if (c === 1) ans += x;
return ans;
}
Complexity
- ⏰ Time complexity:
O(n)– We scannumsonce to build counts and once over a bounded range (1..100) to sum unique values. - 🧺 Space complexity:
O(1)– The counting array has fixed size (101), independent ofn.