I want to count the unique values in a given array without altering the original array but the solution has to be within the time complexity of O(n)
. so far all of the solutions I've seen, have a time complexity of O(n^2)
like here. I can't find the error in my solution's logic. I'm new to Data Structure & Algorithms and would like a simple solution.
MY CODE -
const countUniqueValues = (arr) =>{
if(arr.length === 0){
return console.log(arr.length);
}else if(arr.length === 1){
return console.log(arr.length);
}
const unique = [];
let i = 0;
for( let j = 1; j < arr.length; j++){
if(arr[i] !== arr[j]){
i ++;
unique.push(arr[i]);
}
}
return console.log(unique);
}
//test cases
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
Wrong Output -
[ 1 ]
[
2, 3, 4, 4,
4, 7, 7, 12
]
0
[ -1, -1, 0 ]