Tackling Algorithms: Counting Unique Values

Problem: Given an array of integers, count the number of unique values.

For example, if we have the following array:

[1, 1, 1, 1, 1, 1, 3, 5]

the count of original values is 3 => 1, 3, and 5.

First Solution: Frequency Counter

The first time I attempted this problem I decided to: 1. Create an empty object, and for every integer encountered either2. Add that integer to the object or, if that integer is already in the object 3. Increment its value by 1.

Second Solution: Multiple Pointers

If they are equal move j ahead until we find something that is not equal to i.

If they are not equal move i up 1 space and put the value of j into i's new place.

Continue to do this until you have gone through the array completely. 'i' will be at the index of the final unique value. If we add 1 to this index number we will have the total number of unique values.

After we have gone completely through the array one time every unique value is at the beginning of the array and 'i' is in the position of the final unique value:

We see that i is at index 3 so we just add 1 to this to get 4 which is the total number of unique values:

return i + 1

Because we are adding 1 to i this become a problem when we are given an empty array, []. If we were to use the above solution we would get a return value of 1. To combat this we can add a check to the beginning of the function to check for empty arrays:

As you can see, the second solution to this problem only runs through the array once and there was no need to create an additional object or count the number of keys of that object so this second solution is much more efficient than the first. Although both solutions should have time complexity of O(n), the second solution is an improvement when it comes to space complexity.