Sum Of Unique Elements Problem


Description

LeetCode Problem 1748.

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:

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

Example 2:

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

Example 3:

1
2
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.


Solution

We can use a hash table to count the frequency of each number. We then scan through the hash table, and add up the numbers that has the frequency of 1. The time complexity is O(n), and the space complexity is O(n).


Sample C++ Code

This is a C++ solution using a hash table.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    int sumOfUnique(vector<int>& nums) {
        unordered_map<int, int> map;
        unordered_map<int, int>::iterator it;
        
        int count = 0;
        
        for (int i:nums) {
            map[i]++;
        }
        
        for (it = map.begin(); it != map.end(); it++) {
            if (it->second == 1) {
                count += it->first;
            }
        }
        
        return count;
    }
};




Related Posts

X Of A Kind In A Deck Of Cards Problem

LeetCode 914. In a deck of cards, each card has...

Word Subsets Problem

LeetCode 916. You are given two string arrays words1 and...

Vowel Spellchecker Problem

LeetCode 966. Given a wordlist, we want to implement a...

Verifying An Alien Dictionary Problem

LeetCode 953. In an alien language, surprisingly, they also use...

Unique Morse Code Words Problem

LeetCode 804. International Morse Code defines a standard encoding where...

Unique Email Addresses Problem

LeetCode 929. Every valid email consists of a local name...