Skip to content

Instantly share code, notes, and snippets.

@mustafadalga
Last active September 11, 2021 13:54
Show Gist options
  • Save mustafadalga/4e24655e95d8b60254ccfb4ee8126c76 to your computer and use it in GitHub Desktop.
Save mustafadalga/4e24655e95d8b60254ccfb4ee8126c76 to your computer and use it in GitHub Desktop.
Multiple Pointers Count Unique Values Challenge:Implement a function called countUniqueValues, which accepts a sorted array, and counts the unique values in the array. There can be negative numbers in the array, but it will always be sorted.
function countUniqueValues(array){
if(array.length==0)return 0;
let i=0;
for (let j = 1; j < array.length; j++) {
if(array[i]!=array[j]){
i++;
array[i]=array[j];
}
}
return i+1;
}
console.log(
countUniqueValues([1,1,1,1,1,2]), // 2
countUniqueValues([1,2,3,4,4,4,7,7,12,12,13]), // 7
countUniqueValues([]), // 0
countUniqueValues([-2,-1,-1,0,1]) ,// 4
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment