Remove Duplicates from Sorted Array

easy

You're given an integer array nums that is already sorted in non-decreasing order. Some values repeat, and repeats always sit next to each other. Your job is to remove the duplicates in place so that every unique value appears exactly once, while keeping their original relative order.

Let k be the number of unique values. After you're done:

  • Return the integer k.
  • The first k slots of nums must hold those unique values in sorted order.
  • Whatever is left beyond index k - 1 doesn't matter — the judge ignores it.

You must do this in place with O(1) extra space in the optimal solution — no allocating a second array whose size grows with the input.

Hints

The array is already sorted. What does that guarantee about where identical values sit relative to each other?
If every duplicate is a neighbor of the value it copies, you never have to look further back than the last value you decided to keep.
Use two pointers: a slow write index marking the next unique slot and a fast read index scanning ahead. Advance write only when you hit a value different from the one already there.

Common doubts

Because nums is sorted, every occurrence of a value is contiguous. Once you move past a value it can never reappear later, so the only element you can collide with is the most recent unique one.
No. Only the first k elements are validated. Anything after them is leftover and completely ignored.

Interview follow-ups

Keep the same two-pointer skeleton, but compare nums[i] against nums[k - 2] instead of nums[k - 1], so a value is allowed to survive twice — the "keep at most two duplicates" variant.
You lose the adjacency guarantee, so you'd either sort first (O(n log n)) or track seen values in a hash set (O(n) extra space) — the O(1)-space trick relies on the input being sorted.

Fun facts

  • The 'slow write, fast read' two-pointer pattern is the same engine behind Remove Element, Move Zeroes, and the partition step of quicksort.
  • The overwrite is always safe because the write index k never overtakes the read index i — you only ever stomp on cells you've already read.

Asked at

AmazonMicrosoftGoogleAdobeBloomberg
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,1,2]
Output: 2
The unique values are 1 and 2, so k = 2 and the first two slots become [1, 2, _]. The trailing slot is ignored.
Example 2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5
The unique values are 0, 1, 2, 3, 4, so k = 5 and the first five slots become [0, 1, 2, 3, 4, _, _, _, _, _].
Constraints

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

Solve this problem →