Write uniques into the prefix
Because the array is sorted, duplicates are adjacent. w is the next write slot; a new value gets copied there.
The first w slots become the unique prefix. The rest of the array is junk the caller ignores.
Algorithm
- Start
w = 1(the first value is already unique). - For each later
x, if it differs fromnums[w-1], write it atwand incrementw. - Return
w.
- Time
- O(n)
- Space
- O(1)
class Solution: def removeDuplicates(self, nums: list[int]) -> int: if not nums: return 0 w = 1 for i in range(1, len(nums)): if nums[i] != nums[w - 1]: nums[w] = nums[i] w += 1 return w