Two Pointers Rearranging in place
164. Remove Duplicates from Sorted Array
You are given an array of integers nums sorted in non-decreasing order, so each element is greater than or
equal to the one before it. Some values appear more than once. Remove the extra copies so that each value
appears only once.
Change nums itself. Return k, the number of distinct values, and leave those k values in the first k
positions of nums, in the order they appear. What nums holds after the first k positions does not
matter.
The output shows the first k elements of nums after your function returns.
Aim for a single pass over the array with only O(1) extra memory.
Example 1
Input: nums = [1, 1, 2, 3, 3, 3, 7]
[1,2,3,7]Explanation: The distinct values are 1, 2, 3 and 7. The function returns 4, and the first four elements of nums are
[1,2,3,7].
Example 2
Input: nums = [-4, -4, 0, 0, 0]
[-4,0]Explanation: Negative values and zero are kept like any other value. The function returns 2.
Example 3
Input: nums = [9, 9, 9, 9]
[9]Explanation: Every element holds the same value, so the function returns 1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 109numsis sorted in non-decreasing order.
Clarifying questions
What you would ask an interviewer before writing any code.