Tackling Algorithms: Counting Unique Values

Denise Pen on February 04, 2019

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,... [Read Full]
markdown guide

One clever solution is to use Set as they have unique values by design:

function countUniqueValues(arr) {
  return new Set(arr).size;
countUniqueValues([]); // => 0
countUniqueValues([1, 1, 1, 2, 3, 3]); // => 3

It's not really an algorithm, tho ;)


... and a lazy solution would be to use underscorejs:

_.uniq([1, 1, 1, 2, 3, 3]).length; //=> 3

My code wouldn't have been that concise but exact solution I thought of


Right... I always forget about sets!

That makes everything so much easier.


I think also you could use this technique I wrote in this post: dev.to/adtm/whats-your-favorite-al... :)

negating numbers on the fly and checking if they exist, if it doesn't - add +1 to the counter.


What happens when the array isn't pre-sorted?


If it's not pre-sorted you have to use a different approach - the multiple pointers approach won't work.

code of conduct - report abuse