Count the number of unique values in a sorted array efficiently. This is a fundamental problem that demonstrates important algorithmic techniques.
Example:
countUniqueValues([1,1,2,3,3,4,5,5,5,6]) // Returns 6
Most readable solution using JavaScript's built-in Set:
function countUniqueValues(arr) {
return new Set(arr).size;
}
function countUniqueValues(arr) {
if (!arr.length) return 0;
const seen = {};
for (const num of arr) {
seen[num] = true; // Mark value as seen
}
return Object.keys(seen).length;
};
Explanation:
function countUniqueValues(arr) {
if (!arr.length) return 0;
let i = 0;
for (let j = 1; j < arr.length; j++) {
if (arr[i] !== arr[j]) {
i++;
arr[i] = arr[j];
}
}
return i + 1;
}
Explanation:
The two-pointer technique requires sorted input because it relies on these key properties:
Without sorting, duplicates may be scattered, breaking the algorithm's core logic.
| Approach | Time Complexity | Space Complexity | Modifies Input | Works with Unsorted | Best Use Case |
|---|---|---|---|---|---|
| Two-Pointer | O(n) | O(1) | ✅ Yes | ❌ No | Large sorted arrays |
| Hash Map | O(n) | O(n) | ❌ No | ✅ Yes | Unsorted arrays, general purpose |
| Set Conversion | O(n) | O(n) | ❌ No | ✅ Yes | Small/medium arrays, readability |
| Sort + Two-Pointer | O(n log n) | O(1)* | ✅ Yes | ✅ (after sort) | Large unsorted arrays (if modifiable) |
*Assumes in-place sorting. If creating a new sorted array, space becomes O(n).
That's it for the counting unique values algorithm. I hope you learned as much as I did. If you have any questions or suggestions, please hit me up !
Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.
Feel free to me through this learning journey by providing any feedback and if you wanna support me: