Challenge #17 - Sum of Unique Elements.
Tags: programming, codenewbie, javascript, beginners
Published: 2021-10-05 07:04:31

Helllllooooo!

Pretty much excited about today's problem (No, 17 is not my lucky number.) Cool, let's directly jump to the challenge for Day #17 of [my coding diary](https://www.pankajtanwar.in/coding-diary).

<hr/>

**Problem of the day** - [Sum of Unique Elements](https://leetcode.com/problems/sum-of-unique-elements/)

**Tag** - Easy 

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.

<hr/>

The problem is quite easy to understand. Now, after solving some good number of problems, I feel, multiple approaches are striking to my mind instantly, after reading the problem statement (or may be the problems are easy!)

<hr/>

So, we need to find the sum of only unique elements in the array. Ummm, as of now I can think of three approaches. 

### 1. My all-time savior best friend, Hashmap

- Loop over the list, save the count of each element in the hashmap
- Loop over the list again, if the count is 1, add else tata-bye-bye
- just return the final result

**Here is the code** -

```cpp
class Solution {
public:
    int sumOfUnique(vector<int>& nums) {
        int res = 0;
        map<int,int> hash;        
        for(int num: nums) {
            hash[num]++;
        }
        
        for(int num: nums) {
            if(hash[num] == 1) res += num;
        }
        return res;
    }
};
```


Pretty nice solution. 

### 2. Using sort

- Sort the list
- Loop over the list and just check if the previous element is the same (means element is duplicated), skip that

Ahh, please don't be angry with me for not coding the solution for this. It would be a too slow approach, `O(n log n)`. And I don't like leetcode rewarding me for the slowest submission ever!

### 3. Using a constant array

Whenever I see the constraints are too small, my mind automatically starts thinking of having a constant array. We can replace the hashmap with a constant array here.

Ummm, can I do it one pass only?  let's try!

```cpp
class Solution {
public:
    int sumOfUnique(vector<int>& nums) {
        int res = 0;
        int arr[101] = {0};
        
        for(int num: nums) {
            if(arr[num] == 0) {
                res += num;
                arr[num]++;
            } else if(arr[num] == 1) {
                res -= num;
                arr[num] = -1;
            }
        }
        return res;
    }
};
```

So, what I am doing here?

- Keep a constant array of length 101
- If, number is not repeated, add it to final result and increase the count 
- If number is repeated, I deduct that number and assign the count of that number to -1 (means I don't want to see this again in my life)

Pretty simple right? 

Oh man, I just checked this guy has [7 solutions for this problem](https://leetcode.com/problems/sum-of-unique-elements/discuss/1052455/C%2B%2B-7-Solutions).

As always, if you have any thoughts about anything shared above, don't hesitate to [reach out](https://twitter.com/the2ndfloorguy).

<hr/>

You might like previous editions of [my coding diary](/coding-diary)

- [Day #16 - Best Time to Buy and Sell Stock.](https://www.pankajtanwar.in/code/best-time-to-buy-and-sell-stock/)
- [Day #15 - Count Number of Pairs With Absolute Difference K.](https://www.pankajtanwar.in/code/count-number-of-pairs-with-absolute-difference-k/)
- [Day #14 - Minimum Number of Operations to Move All Balls to Each Box.](https://www.pankajtanwar.in/code/minimum-number-of-operations-to-move-all-balls-to-each-box/)
- [Day #13 - Number Of Rectangles That Can Form The Largest Square.](https://www.pankajtanwar.in/code/number-of-rectangles-that-can-form-the-largest-square/)
- [Day #12 - Unique Morse Code Words.](https://www.pankajtanwar.in/code/unique-morse-code-words/)
- [Day #11 - Count the Number of Consistent Strings.](https://www.pankajtanwar.in/code/count-the-number-of-consistent-strings/)
- [Day #10 - Find Greatest Common Divisor of Array.](https://www.pankajtanwar.in/code/find-greatest-common-divisor-of-array/)