You are given an integer array nums sorted from smallest to largest, where values may repeat. Remove the duplicates in place so that each distinct value appears only once, keeping the values in their original order, and return k, the number of distinct values.
After the call, the first k elements of nums must be the distinct values in their original (ascending) order. Whatever is stored at index k and later does not matter. Do the work in place, using O(1) extra memory.
Function Signature
def remove_duplicates(nums: list[int]) -> int:
...
Rules
-
nums
is a Python list that the function modifies in place. The return value is
k
, the number of distinct values in the input.
-
The result is checked by reading the returned
k
and the slice
nums[:k]
, which must equal the distinct values of the input in ascending order. Elements from index
k
onward are ignored, so any values may remain there.
-
Rebinding the name
nums
to a new list inside the function does not change the caller's list, so the check would see the original contents.
Constraints
-
1 <= len(nums) <= 10^4
-
-10^4 <= nums[i] <= 10^4
-
nums
is sorted in non-decreasing order.
Examples
Input: nums = [2, 2, 3]
Output: 2, nums = [2, 3, _]
The distinct values are 2 and 3, so k = 2 and the first two slots hold [2, 3]. The _ marks a slot whose value is ignored.
Input: nums = [1, 1, 2, 2, 3, 4, 4, 5]
Output: 5, nums = [1, 2, 3, 4, 5, _, _, _]
Five distinct values appear (1 through 5). Each is kept once, in ascending order, in the first five slots.
Input: nums = [-4, -4, -4, -4]
Output: 1, nums = [-4, _, _, _]
Every element is equal, so one distinct value remains and nums[0] stays -4.