Remove Duplicates from Sorted Array

easy · arrays, two pointers

Remove Duplicates from Sorted Array

You are given a sorted slice of integers nums. Remove duplicates in-place so that each unique value appears once in the first part of the slice. Return the number of unique values.

The first k elements of nums should contain the unique values in order. Elements after index k-1 can be anything.

Function signature

func RemoveDuplicates(nums []int) int

In Python, implement remove_duplicates(nums).

Example

nums = [1,1,2,2,3]
return 3
nums (first 3) = [1,2,3]

Constraints

  • 1 <= len(nums) <= 200_000
  • nums is sorted in non-decreasing order

Aim for O(n) time and O(1) extra space.

Try it before coding

An input of [1,1,7,7] is left as [1,7,7,7] and the function returns 2. Is the result complete?

Check your reasoning

Yes. The caller reads [1,7] from the first two slots. The extra 7s lie outside the returned prefix.

Run tests to see results
No issues detected
    Join Discord