Back to ArraysRemove Duplicates from Sorted Array
Easy

Remove Duplicates from Sorted Array

EasyRecommendedTwo Pointers

Given a sorted array, remove duplicates in place so each unique value appears once, and return the count of unique values — the first part of the array up to that count holds the result.

Examples

Example 1

Input:
nums = [1,1,2]
Output:
2, with nums = [1,2,_]

Explanation: The first 2 slots of the mutated array hold the unique values 1 and 2, in order; anything after index 1 is irrelevant.

Example 2

Input:
nums = [0,0,1,1,1,2,2,3,3,4]
Output:
5, with nums = [0,1,2,3,4,_,_,_,_,_]

Explanation: Five distinct values exist; the first five slots hold them in ascending order.

Example 3

Input:
nums = [1]
Output:
1, with nums = [1]

Explanation: A single-element array is trivially already unique.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -100 <= nums[i] <= 100
  • nums is sorted in non-decreasing order

Follow-up

How would the write-pointer condition need to change if each distinct value were allowed to appear at most twice instead of once?

Loading editor…

Code execution is coming soon.