Leetcode 1748. Sum of Unique Elements

Problem description

You are given an integer array nums. The unique elements of an array are the elements that appear exactly once in the array. Your task is to return the sum of all the unique elements of nums.

Example

Let's walk through an example:

Input: nums = [1, 2, 3, 2]

Output: 4

Explanation: The unique elements are [1, 3], and the sum is 4.

Approach

The easiest approach to solve this problem is to use a dictionary (HashMap, or object depending on the language) to store the count of each number in the array. Then, iterate through the dictionary, summing up the values whose keys have a count of 1 (unique).

Steps

  1. Initialize an empty dictionary to store the occurrence count of each number
  2. Loop through the input array nums, updating the dictionary with the count for each element
  3. Initialize a variable sum to store the sum of unique elements
  4. Iterate through the dictionary, checking if the element count is 1 (unique), and adding it to sum
  5. Return sum as the final result

Solution

Now, let's implement the solution for each language.

Python

1class Solution:
2    def sumOfUnique(self, nums):
3        # Step 1: Initialize an empty dictionary to store the occurrence count of each number
4        count = {}
5        
6        # Step 2: Loop through the input array nums, updating the dictionary with the count for each element
7        for num in nums:
8            if num in count:
9                count[num] += 1
10            else:
11                count[num] = 1
12                
13        # Step 3: Initialize a variable `sum` to store the sum of unique elements
14        sum = 0
15        
16        # Step 4: Iterate through the dictionary, checking if the element count is 1 (unique), and adding it to `sum`
17        for num, occurrence in count.items():
18            if occurrence == 1:
19                sum += num
20                
21        # Step 5: Return `sum` as the final result
22        return sum

Java

1import java.util.HashMap;
2import java.util.Map;
3
4class Solution {
5    public int sumOfUnique(int[] nums) {
6        // Step 1: Initialize an empty dictionary to store the occurrence count of each number
7        Map<Integer, Integer> count = new HashMap<>();
8        
9        // Step 2: Loop through the input array nums, updating the dictionary with the count for each element
10        for (int num : nums) {
11            count.put(num, count.getOrDefault(num, 0) + 1);
12        }
13        
14        // Step 3: Initialize a variable `sum` to store the sum of unique elements
15        int sum = 0;
16        
17        // Step 4: Iterate through the dictionary, checking if the element count is 1 (unique), and adding it to `sum`
18        for (Map.Entry<Integer, Integer> entry : count.entrySet()) {
19            if (entry.getValue() == 1) {
20                sum += entry.getKey();
21            }
22        }
23        
24        // Step 5: Return `sum` as the final result
25        return sum;
26    }
27}

JavaScript

1class Solution {
2    sumOfUnique(nums) {
3        // Step 1: Initialize an empty dictionary to store the occurrence count of each number
4        const count = {};
5        
6        // Step 2: Loop through the input array nums, updating the dictionary with the count for each element
7        for (const num of nums) {
8            if (count[num]) {
9                count[num]++;
10            } else {
11                count[num] = 1;
12            }
13        }
14        
15        // Step 3: Initialize a variable `sum` to store the sum of unique elements
16        let sum = 0;
17        
18        // Step 4: Iterate through the dictionary, checking if the element count is 1 (unique), and adding it to `sum`
19        for (const [num, occurrence] of Object.entries(count)) {
20            if (occurrence === 1) {
21                sum += parseInt(num);
22            }
23        }
24        
25        // Step 5: Return `sum` as the final result
26        return sum;
27    }
28}

C++

1#include <unordered_map>
2
3class Solution {
4public:
5    int sumOfUnique(std::vector<int>& nums) {
6        // Step 1: Initialize an empty dictionary to store the occurrence count of each number
7        std::unordered_map<int, int> count;
8        
9        // Step 2: Loop through the input array nums, updating the dictionary with the count for each element
10        for (int num : nums) {
11            ++count[num];
12        }
13        
14        // Step 3: Initialize a variable `sum` to store the sum of unique elements
15        int sum = 0;
16        
17        // Step 4: Iterate through the dictionary, checking if the element count is 1 (unique), and adding it to `sum`
18        for (const auto &num_count_pair : count) {
19            if (num_count_pair.second == 1) {
20                sum += num_count_pair.first;
21            }
22        }
23        
24        // Step 5: Return `sum` as the final result
25        return sum;
26    }
27};

C#

1using System;
2using System.Collections.Generic;
3
4public class Solution {
5    public int SumOfUnique(int[] nums) {
6        // Step 1: Initialize an empty dictionary to store the occurrence count of each number
7        Dictionary<int, int> count = new Dictionary<int, int>();
8        
9        // Step 2: Loop through the input array nums, updating the dictionary with the count for each element
10        foreach (int num in nums) {
11            if (count.ContainsKey(num)) {
12                count[num]++;
13            } else {
14                count[num] = 1;
15            }
16        }
17        
18        // Step 3: Initialize a variable `sum` to store the sum of unique elements
19        int sum = 0;
20        
21        // Step 4: Iterate through the dictionary, checking if the element count is 1 (unique), and adding it to `sum`
22        foreach (KeyValuePair<int, int> entry in count) {
23            if (entry.Value == 1) {
24                sum += entry.Key;
25            }
26        }
27        
28        // Step 5: Return `sum` as the final result
29        return sum;
30    }
31}

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫