Skip to content

Instantly share code, notes, and snippets.

@Jimmydalecleveland
Created June 23, 2019 19:48
Show Gist options
  • Save Jimmydalecleveland/03be53f7d6158a2a63575cf1911b377d to your computer and use it in GitHub Desktop.
Save Jimmydalecleveland/03be53f7d6158a2a63575cf1911b377d to your computer and use it in GitHub Desktop.
Given an array of sorted values, return the number of unique values with O(n) complexity
/*
** Given an array of sorted values, return the number of unique values
**
** Method: Use 2 pointers (lastUniqueIndex and i) to mutate sorted array and
** return lastUniqueIndex + 1 for result
*/
function countUniqueValues(arr) {
if (!arr.length) return 0
let lastUniqueIndex = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[lastUniqueIndex] !== arr[i]) {
lastUniqueIndex++
arr[lastUniqueIndex] = arr[i]
}
}
return lastUniqueIndex + 1
}
countUniqueValues([1, 1, 2]) // 2
countUniqueValues([1, 2, 3, 3, 4]) // 4
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