InterviewPrepKit

Home / Coding / Two Pointers

Remove Duplicates from Sorted Array II

medium Original ↗
Solving tips
  • Read/write two pointers: keep nums[x] exactly when write < 2 OR x != nums[write-2], which detects a would-be third copy in one comparison.
  • Compare against the OUTPUT prefix nums[write-2], not nums[read-2]; the input side still holds copies you already skipped.
  • The write < 2 guard matters: the first two elements are always kept and nums[write-2] would wrap on a negative index in Python.
  • O(n) time, O(1) space, one pass; return k (the count). The nums[write-K] pattern generalizes to 'at most K copies'.

Problem

You are given an integer array nums sorted in non-decreasing order. Rewrite it in place so that each distinct value appears at most twice, keeping the relative order of the kept elements, and return k — the number of elements kept.

The first k slots of nums must hold the answer; whatever sits beyond index k - 1 is ignored by the judge. You must not allocate a second array — O(1) extra memory is required.

Examples

Example 1

Input:  nums = [1, 1, 1, 2, 2, 3]
Output: 5, nums = [1, 1, 2, 2, 3, _]

The third 1 is dropped; everything else appears at most twice already.

Example 2

Input:  nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
Output: 7, nums = [0, 0, 1, 1, 2, 3, 3, _, _]

Two of the four 1s are dropped.

Example 3

Input:  nums = [5, 5]
Output: 2, nums = [5, 5]

Exactly two copies is allowed — nothing changes.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.
  • O(1) extra space — the in-place requirement is the whole problem; a single pass is expected.

Think about it first

Hint 1 Keep two pointers: `read` scans every element, `write` marks where the next kept element lands. When should `read`'s element be kept?
Hint 2 Because the kept prefix is sorted too, "would this make three in a row?" can be answered by looking at just one already-written slot. Which one?
Hint 3 Keep `nums[read]` exactly when `write < 2` or `nums[read] != nums[write - 2]`. If the incoming value equals the element two slots back in the output, it would be a third copy — skip it. One pass, no counters needed.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.