Given an integer array nums
, return the sum of all the unique elements of nums
. Unique elements are those elements that appear exactly once in the array.
This method ensures that we count in a single pass through the array (O(n)), and then sum by iterating through the dictionary (O(u), where u is the number of unique elements).
def sum_of_unique(nums):
frequency = {}
# Traverse through the array and count the frequency of each element
for num in nums:
if num in frequency:
frequency[num] += 1
else:
frequency[num] = 1
# Sum up the keys where the count is 1 (unique elements)
unique_sum = 0
for num, count in frequency.items():
if count == 1:
unique_sum += num
return unique_sum
Let’s go through an example:
nums = [1, 2, 3, 2]
print(sum_of_unique(nums)) # Expected output: 4, since 1 and 3 are unique and their sum is 4.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?