easy +10 pts

Remove Duplicates from Sorted Array

Remove duplicates in-place from a sorted list and return the new length.

Write a function `remove_duplicates(nums: List[int]) -> int` that takes a sorted list of integers `nums` and removes the duplicates **in-place** such that each element appears only once. The relative order of the elements must be kept the same. The function should return the new length of the list after duplicates are removed. Do not allocate extra space for another list; you must do this by modifying the input list in-place with O(1) extra memory. The first `k` elements of `nums` after the function should hold the final result; the elements beyond `k` do not matter.

Constraints

The input list may be empty (0 ≤ len(nums) ≤ 10^5). The list is guaranteed to be sorted in non-decreasing order. Integers may be negative, zero, or positive. Expected time complexity: O(n), where n = len(nums). Expected extra space complexity: O(1).

Example

>>> nums = [1,1,2]
>>> remove_duplicates(nums)
2
>>> nums[:2]
[1, 2]

>>> nums = [0,0,1,1,1,2,2,3,3,4]
>>> remove_duplicates(nums)
5
>>> nums[:5]
[0, 1, 2, 3, 4]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use two pointers: one for reading through the list, one for writing the next unique element.
Whenever you see a value different from the last written one, copy it to the write position and advance.
Remember to handle the empty list case.
The first element is always kept if the list is non-empty.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.