Algorithm to Sum of Unique Elements


You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Return the sum of all the unique elements of nums.

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

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

Example 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

Sum of Unique Elements

We use the Counter to count the frequencies for each number in the list, then we go through each number to see if the number is unique (frequency = 1) and sum them up.

1
2
3
4
5
6
7
8
class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        x = Counter(nums)
        ans = 0
        for i in nums:
            if x[i] == 1:
                ans += i
        return ans
class Solution:
    def sumOfUnique(self, nums: List[int]) -> int:
        x = Counter(nums)
        ans = 0
        for i in nums:
            if x[i] == 1:
                ans += i
        return ans

The time complexity is O(N) and the space complexity is also O(N).

GoLang: Sum of Unique Elements

The following is the GoLang implementation using a Hash map.

1
2
3
4
5
6
7
8
9
10
11
12
13
func sumOfUnique(nums []int) int {
    var c = make(map[int]int)
    for _, i := range nums {
        c[i] += 1
    }
    var ans = 0
    for i, j := range c {
        if j == 1 {
            ans += i
        }
    }
    return ans
}
func sumOfUnique(nums []int) int {
    var c = make(map[int]int)
    for _, i := range nums {
        c[i] += 1
    }
    var ans = 0
    for i, j := range c {
        if j == 1 {
            ans += i
        }
    }
    return ans
}

See also: Teaching Kids Programming – Sum of Unique Elements

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
328 words
Last Post: Teaching Kids Programming - Breadth First Search Algorithm to Check if All Leaves in Same Level of Binary Tree
Next Post: Teaching Kids Programming - Compute the Number of Set Bits in an Integer

The Permanent URL is: Algorithm to Sum of Unique Elements

Leave a Reply