Given a sorted integer array nums, remove duplicates in-place such that each unique element appears only once. Return the count of unique elements k. The first k elements of nums must hold the unique values.
nums = [1,1,2]k=2, nums=[1,2,_]Since the array is sorted, duplicates are adjacent. The slow pointer holds the last accepted unique value. Fast advances through duplicates without writing. The moment fast finds a different value, slow advances one step and receives the new unique — overwriting the now-useless duplicate position.
Building a new array of unique values uses O(n) extra space. The problem asks you to do it in place.
Because the array is sorted, duplicates sit next to each other. Keep a write pointer k, which marks the end of the unique part. A read pointer scans ahead, and copies a value forward only when it differs from the last unique one.
A slow write pointer and a fast read pointer compact an array in place. In a sorted array, a value is new exactly when it differs from the last kept value.
Run the animation above on your own input, or watch the 1:31 video explanation of Remove Duplicates from Sorted Array with a dry run and Java code.