CodingNodes / Arrays & Hashing / Remove Duplicates from Sorted Array System design Space play · ←→ step · R restart

Problem

The array nums is sorted from small to large and may contain repeated numbers. Remove the repeats in place so that every distinct value appears exactly once, keeping the original order.

Let k be the number of distinct values. Rearrange nums so that its first k items are those distinct values in order, then return k. What sits after position k is ignored.

Constraints

  • 1 ≤ nums.length ≤ 3 · 10⁴
  • -100 ≤ nums[i] ≤ 100
  • nums is sorted in non-decreasing order

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(1)

Time: The read index i visits each item once.

Space: Only the indexes i and k are stored.

Because the array is sorted, a number is new exactly when it differs from the last number we kept, nums[k - 1]. Read with i and write with k: each new value is copied to nums[k] and k moves on. Duplicates are skipped. k never gets ahead of i, so nothing is overwritten before it has been read.