Sum of Unique Elements | LeetCode 1748 | Python | Solution

Click here to see the problem details.

Problem Overview

This one is a very much simple problem. We have to find out the sum of all the unique values from an integer array. Nothing else, and we don’t have to check anything extra. Let’s see an example.

input: [1, 1, 5, 2]
output: 7

In the above example, it’s clear that 5 and 2 are unique. And the sum of 5 + 2 is 7. 1 appears two times in the given array, so we did not count it.

Coding Part

To solve this problem, we will use a hashtable. In this table, we will store how many times an element appears in the given array.

Then we will check how many elements appeared uniquely to add them to the final result.

Let’s see the code example for better understanding.

class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        appearance = {}
        for num in nums:
            if num in appearance:
                appearance[num] += 1
                appearance[num] = 1
        result = 0
        for key in appearance:
            if appearance[key] == 1:
                result += key
        return result

We can solve this problem using the count method. By the way, the count is a method from Python List. But this one is less efficient than the previous one.

Let’s see the code.

class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        result = 0
        for num in nums:
            if nums.count(num) == 1:
                result += num
        return result

That’s all about the problem solution. I hope it will help you.