Problem Statement:
We have a sorted array and we have to count the unique number and print this.
CODE in JavaScript:
function countUnique(array){
if(array.length){
let i=0;
for(let j=1;j<array.length;j++){
if(array[i]!=array[j]){
i++;
array[i]=array[j];
}
}
return i+1;
}
else
throw new Error("Array is empty");
}
const result=countUnique([1,1,2,2,2,3,4,5,5,6,7,7,7]);
console.log(result);
//Output-> 7
//complexity -> O(n)
Comments
Post a Comment