Remove duplicates from a sorted array in-place and return the count of unique elements.
Problem
You are given a non-decreasing sorted integer array nums. Remove the duplicates in-place so that each distinct value appears exactly once in the beginning of the array.
After the operation, the first part of nums should contain the unique values in the same relative order. The remaining portion of the array does not matter.
Return the number of unique elements.
Goal
Modify the array using only extra space and keep the operation efficient.
Example behavior
If nums = [1,1,2], after processing the array may become [1,2,_] and the function should return 2.
If nums = [0,0,1,1,1,2,2,3,3,4], after processing the array may become [0,1,2,3,4,_,_,_,_,_] and the function should return 5.
Input Format
- A single integer array
numssorted in non-decreasing order.
Output Format
- Return an integer
k, the number of unique values. - The first
kpositions ofnumsshould contain the unique values after in-place modification.
Constraints
numsis sorted in non-decreasing order.- You must modify the array in-place.
- Use extra space.
- The order of the unique elements must be preserved.
Example 1
Input
nums = [1,1,2]
Output
2
Explanation
The unique values are [1,2]. After updating in place, the first two positions contain these values.
Example 2
Input
nums = [0,0,1,1,1,2,2,3,3,4]
Output
5
Explanation
The unique values are [0,1,2,3,4]. The array is modified in place so those values occupy the first five positions.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.