Sum of Unique Elements
For this blog, I’ll be going over another popular problem on LeetCode. Note that I’ll be using JavaScript to solve this problem! Here’s the prompt:
In other words, the prompt is asking us to create a function that takes in an array of integers (nums
) and returns the sum of the unique elements inside of nums
. Unique elements are the elements that only appear once in the array! For example 1, we can see that the output is 4
because the only Unique values in the array are 1
and 3
and adding those two numbers gives you 4
. Example 2 is a bit different because the output is 0
. This means that there are no Unique elements. Before doing any code, the first step should always be planning ahead or pseudo code. So let’s start with that! Here’s a picture of my pseudo code:
Now that we know what to do, let’s go through each step together!
The first two steps mention that we need to create a variable that’s going to represent the hash table and create another variable that represents the sum of the unique elements. Here’s what the code should look like right now:
Next, I’ll need to create a for of
loop that iterates over nums
. Inside of this for of
loop, I’ll have to create a conditional that states, if the current number being iterated in nums
exists inside of uniqueHash
, then increment that number by one. Here’s what the code should look like so far:
Now that the current number being iterated in nums (nums[i]
) is added inside of uniqueHash
, I now have to create a for in
loop. This for in
loop is going to iterate over uniqueHash
and also manipulate the value of uniqueSum
. Inside of the for in
loop, I’ll create a conditional that sets uniqueSum
plus equal (+=
) to the key inside of uniqueHash
if the key’s value is less than 2. Here’s what the code should look like so far:
The final step would be returning uniqueSum
outside of the for in
loop. Here’s the full solution:
Here are the results for lines 29–30:
Here’s the solution on LeetCode:
I hope this blog was helpful in any way! For more info on for of
loops, for in
loops, hash tables, and built in methods such as parseInt()
checkout the resource section below!