Remove Duplicates from Sorted Array

Easy

Problem

Remove duplicates from a sorted array in place so that each value appears once, keeping the order. Return k, the number of unique values. The first k slots must hold them; what comes after does not matter.

Example 1

Input:  [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: k = 5, array starts [0, 1, 2, 3, 4, …]

Test cases

Case 1

Input:    [1,1,2]
Expected: 2

Case 2

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

Case 3

Input:    []
Expected: 0

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Slow write pointer

Time O(n)Space O(1)

k marks the end of the unique prefix; copy a value forward only when it differs from the last kept value.

function removeDuplicates(nums) {
let k = 0;
for (const x of nums) if (k === 0 || x !== nums[k - 1]) nums[k++] = x;
return k;
}

Variant "allow at most two": compare with nums[k - 2] instead.