Skip to content

Instantly share code, notes, and snippets.

@therealbigzeez
Created December 4, 2023 18:43
Show Gist options
  • Select an option

  • Save therealbigzeez/3680449ee52872082b310e865c10b5a9 to your computer and use it in GitHub Desktop.

Select an option

Save therealbigzeez/3680449ee52872082b310e865c10b5a9 to your computer and use it in GitHub Desktop.
Multiple Pointers - countUniqueValues
function countUniqueValues(arr) {
if (arr.length === 0) {
return 0;
}
let i = 0; // Slow pointer
for (let j = 1; j < arr.length; j++) {
if (arr[i] !== arr[j]) {
i++;
arr[i] = arr[j];
}
}
return i + 1;
}
@therealbigzeez
Copy link
Author

This function uses two pointers, where i represents the slow pointer and j represents the fast pointer. The loop iterates through the array, and whenever a unique value is found, the slow pointer is moved, and the unique value is placed at the slow pointer's position in the array. Finally, the count of unique values is given by i + 1. This approach has O(1) space complexity and O(n) time complexity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment