SDE & MLE Prep

26. Remove Duplicates from Sorted Array

Problem

Given a sorted array nums, remove the duplicates in place so each value appears once, keeping the original order. Return the number k of unique values; the first k slots of nums must hold them (what's after doesn't matter).

Example: [0,0,1,1,1,2,2,3,3,4] → 5, with nums starting [0,1,2,3,4]

Constraints: O(1) extra space.

Slow pointer k marks the end of the unique prefix; fast pointer scans. Copy whenever a new value appears.

Complexity: O(n) time, O(1) space.

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 0
        for x in nums:
            if k == 0 or x != nums[k - 1]:
                nums[k] = x
                k += 1
        return k