Implement a function CountUniqueValues
, which takes in a sorted Array of positive and negative integers.
It should count and return the number of unique values in the Array.
Thoughts:
- This is an easy question.
- It should be easily checked against using JavaScript.
- It should try to use pointers to track the position of values to be compared against.
- No need to mutate the original Array.
function CountUniqueValues(arr) { if (arr.length === 0) return 0; let uniqueValueIndex = 0; let counter = 1; for (let i = 1; i < arr.length; i++) { if (arr[i] !== arr[uniqueValueIndex]) { counter++; uniqueValueIndex = i; } } return counter; } // sample data const sorted_array = [-10,-11,1,1,1,2,3,4,5,5,5,6,7,7,7,7,8]; // result console.warn(CountUniqueValues(sorted_array)); // to be asserted against result console.warn(Array.from(new Set(sorted_array)).length);
Top comments (0)