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

Problem

The array nums is sorted from small to large. Edit it in place so that every value appears at most twice, keeping the original order. Extra copies are dropped.

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

Constraints

  • 1 ≤ nums.length ≤ 3 · 10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • 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.

The first two items can always stay. After that, an item is a third copy exactly when it equals nums[k - 2], the second-to-last item we kept (the array is sorted, so the item in between is the same value too). Skip those. Copy any other item to nums[k] and move k on. Compared with the plain duplicate-removal problem, only the look-back distance changes from 1 to 2.