InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Two Pointers

Remove Duplicates from Sorted Array II

medium Original ↗ 00:00

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; anything 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; 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug