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

1
2
3
Input: nums = [1,2,3,2]
Output: 4
Explanation: The unique elements are [1,3], and the sum is 4.

Example 2

1
2
3
Input: nums = [1,1,1,1,1]
Output: 0
Explanation: There are no unique elements, and the sum is 0.

Example 3

1
2
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 <= 100
  • 1 <= nums[i] <= 100

Solution

Approach

We count the frequency of each number, then sum those that appear exactly once.

Code

C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
1
2
3
4
5
6
7
8
9
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
1
2
3
4
5
6
7
8
9
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
1
2
3
4
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
1
2
3
4
5
6
7
8
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
1
2
3
4
5
6
7
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;
}

Explanation

We count the frequency of each number and sum those that appear exactly once.

Complexity

  • ⏰ Time complexity: O(n)
  • 🧺 Space complexity: O(n)