Sum of Unique Elements

We can create a dictionary to count the frequency of each element in the list. Once we have the frequency count, we can iterate over the dictionary to sum up the unique elements (those with a count of 1).

Here’s the Python code for this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        count = dict()
        for num in nums:
            if num in count:
                count[num] += 1
            else:
                count[num] = 1

        unique_sum = 0
        for key in count:
            if count[key] == 1:
                unique_sum += key

        return unique_sum

This approach works by first building a frequency dictionary count for all numbers in nums. It then goes through the dictionary and sums up all the numbers which have a frequency of 1 (i.e., unique numbers). The sum is then returned.

Single Loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        cnt = [0] * 101
        res = 0
        for n in nums:
            cnt[n] += 1
            if cnt[n] == 1:
                res += n
            elif cnt[n] == 2:
                res -= n
        return res