The "Sum of Unique Elements" problem asks you to find the sum of all unique elements in a given integer array nums
. An element is considered unique if it appears exactly once in the array. You are to return the sum of all such unique elements.
nums
.nums
.nums
can be positive or negative.The core of this problem is to efficiently identify which numbers in the array appear only a single time, then sum them up. The most direct (brute-force) way would be to check, for each element, how many times it appears in the array. If it appears once, add it to the sum. However, this would mean for every element, scanning the entire array, leading to a slow solution.
To optimize, we realize that if we can count the frequency of each number in a single pass, we can then easily find which numbers are unique. This suggests using a data structure that maps each number to its count, such as a hash map (dictionary). This way, we can check uniqueness in constant time per element.
In summary, shift from repeatedly scanning the array (brute-force) to counting all frequencies first, then summing only those with a count of one.
We can break down the solution into clear steps:
nums
.nums
, updating the count for each number.We use a hash map because it allows us to count each number in O(1) time per insertion and lookup, making the overall process efficient.
Let's walk through an example with nums = [1, 2, 3, 2]
:
The optimized solution is much faster and suitable for large arrays.
To solve the "Sum of Unique Elements" problem, we efficiently count how many times each number appears using a hash map, then sum up only those that appear exactly once. This approach is both simple and powerful, leveraging hash maps for fast lookups and insertions. The key insight is to avoid repeated scanning by counting frequencies up front, resulting in an elegant and efficient linear-time solution.
class Solution:
def sumOfUnique(self, nums):
from collections import Counter
count = Counter(nums)
return sum(num for num, freq in count.items() if freq == 1)
class Solution {
public:
int sumOfUnique(vector<int>& nums) {
unordered_map<int, int> count;
for (int num : nums) {
count[num]++;
}
int sum = 0;
for (auto& kv : count) {
if (kv.second == 1) sum += kv.first;
}
return sum;
}
};
class Solution {
public int sumOfUnique(int[] nums) {
Map<Integer, Integer> count = new HashMap<>();
for (int num : nums) {
count.put(num, count.getOrDefault(num, 0) + 1);
}
int sum = 0;
for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
if (entry.getValue() == 1) sum += entry.getKey();
}
return sum;
}
}
var sumOfUnique = function(nums) {
const count = {};
for (const num of nums) {
count[num] = (count[num] || 0) + 1;
}
let sum = 0;
for (const num in count) {
if (count[num] === 1) sum += Number(num);
}
return sum;
};