26. Remove Duplicates from Sorted Array
You receive an integer array nums that is already sorted in non-decreasing order. Compact it in place so that each distinct value survives exactly once, with the survivors staying in sorted order at the front of the array, and return k, the number of distinct values.
After your function finishes, the first k slots of nums must hold the deduplicated sequence; anything left past index k - 1 is simply ignored. Aim to do this without allocating a second array.
Example 1:
Input: nums = [1, 1, 2]
Output: 2, with nums starting [1, 2, _]
Explanation: There are two distinct values, 1 and 2, so k = 2 and the array's first two slots become [1, 2].
Example 2:
Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: 5, with nums starting [0, 1, 2, 3, 4, ...]
Explanation: Five distinct values remain: 0, 1, 2, 3, 4. Whatever sits beyond index 4 afterward does not matter.
Constraints:
- 1 ≤ nums.length ≤ 3 * 10⁴
- -10⁴ ≤ nums[i] ≤ 10⁴
- nums is sorted in non-decreasing order.
Hints:
Because the array is sorted, every duplicate sits immediately after a copy of itself — you only ever need to compare an element with one neighbor.
Keep a slow 'write' index marking where the next new value belongs, and a fast 'read' index scanning ahead. Copy nums[read] down only when it differs from the last value you wrote.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: nums = [1, 1, 2]
Expected output: k = 2, nums → [1, 2]