Remove Duplicates from Sorted Array
1 approach, code in every language
Problem description
Given a sorted integer array, remove the repeated values in place so that each distinct number appears only once, keeping their original ascending order. You may not allocate a second array for the answer.
Return the count k of unique elements. The first k slots of the array must hold those unique values in order; whatever remains beyond position k is irrelevant.
Example 1
Input: nums = [1, 1, 2]
Output: 2, nums = [1, 2, _]
Two distinct values remain, so the leading two slots become 1 and 2.
Example 2
Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: 5, nums = [0, 1, 2, 3, 4, _, _, _, _, _]
Five unique numbers are compacted to the front while the tail is left unchecked.
Constraints
1 ≤ nums.length ≤ 3 * 10^4-10^2 ≤ nums[i] ≤ 10^2nums is sorted in non-decreasing order
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Collapse Repeated Offsets is our own problem on the technique behind Remove Duplicates from Sorted Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free