dsa · easy

Remove Duplicates from a Sorted Array

You are given nums, an array of integers sorted in non-decreasing order. Collapse every run of equal neighbours in place so each distinct value appears once, keeping the original relative order. Return k, the number of distinct values; the first k slots of nums hold the collapsed result and the rest are ignored.

Arguments

An empty array collapses to 0.

Example

nums = [0,0,1,1,1,2,2,3,3,4]

The runs 0,0, 1,1,1, 2,2, 3,3 each shrink to one value and 4 is already unique, so the first five slots become [0,1,2,3,4] and the answer is 5.

[1,1,2] → first two slots [1,2], answer 2.

Constraints

0 <= nums.length <= 3 * 10^4 -100 <= nums[i] <= 100 nums is sorted in non-decreasing order Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.

Examples

Example 1

Input:
[0,0,1,1,1,2,2,3,3,4]

Expected:
5

Example 2

Input:
[1,1,2]

Expected:
2

Example 3

Input:
[]

Expected:
0

Open in the Dojo editor