Created
December 4, 2023 18:43
-
-
Save Robogeek95/3680449ee52872082b310e865c10b5a9 to your computer and use it in GitHub Desktop.
Multiple Pointers - countUniqueValues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.