5. Remove Duplicates from Sorted Array

EasyArrayArray

Given a sorted integer array nums, remove duplicates in-place so each unique element appears only once.

Return k — the number of unique elements. The first k elements of nums must hold the unique values in order.

Do not allocate extra space for another array.

Input: A sorted integer array nums of length n.

Output: An integer k — the count of unique elements.

Examples

Example 1
Input: [1,1,2]
Output: 2
Explanation: k=1. i=1: nums[1]==nums[0] → skip. i=2: nums[2]!=nums[1] → nums[k]=2, k=2. Return 2. Array becomes [1,2,_].
Example 2
Input: [0,0,1,1,1,2,2,3,3,4]
Output: 5
Explanation: Unique values: [0,1,2,3,4]. Write pointer advances only on a new value. Return 5.
Example 3
Input: [1,2,3,4,5]
Output: 5
Explanation: No duplicates. All 5 elements are unique. Return 5.

Constraints

Asked by

BloombergMicrosoftCapgeminiMetaGoogleAmazon
Solve this problem in the editor →