Magicsheet logo

Remove Duplicates from Sorted Array II

Medium
53.4%
Updated 6/1/2025

Remove Duplicates from Sorted Array II

What is this problem about?

The Remove Duplicates from Sorted Array II interview question is a variation of the classic deduplication problem. Given a sorted array, you must remove duplicates in-place such that each unique element appears at most twice. Elements beyond the cutoff do not matter. You must do this in O(1) extra space, returning the new length.

Why is this asked in interviews?

This problem is asked at Apple, Uber, Microsoft, Meta, Amazon, Google, and Bloomberg because it extends the basic two-pointer technique with a generalized condition. It tests whether candidates can adapt a known pattern to a new constraint rather than memorizing a single solution. The underlying concept — allowing at most k occurrences — is a template directly applicable to similar constraints.

Algorithmic pattern used

The pattern is the generalized two-pointer technique. Maintain a write pointer k. For each element nums[i], compare it with nums[k-2] (the element two positions behind the write head). If they differ, it's safe to include nums[i] — write it at position k and advance k. If nums[i] == nums[k-2], it means we already have two copies and must skip. This generalizes to "at most k copies" by comparing with nums[write - k].

Example explanation

Array: [1, 1, 1, 2, 2, 3], at most 2 allowed.

  • k=0,1: First two elements always kept → k=2, array starts as [1,1,...].
  • i=2: nums[2]=1 == nums[k-2]=nums[0]=1 → skip.
  • i=3: nums[3]=2 ≠ nums[k-2]=nums[1]=1 → write 2 at k=2, k=3.
  • i=4: nums[4]=2 ≠ nums[k-2]=nums[2-1]... wait → k=3 now, nums[k-2]=nums[1]=1 ≠ 2 → write 2, k=4.
  • i=5: nums[5]=3 ≠ nums[k-2]=nums[2]=2 (now it's the 2 we wrote) → write 3, k=5.

Result length: 5. Array: [1, 1, 2, 2, 3].

Common mistakes candidates make

  • Hard-coding the comparison to check the previous element only (as in the "at most 1" version), missing the "at most 2" logic.
  • Not initializing k to 2 to allow the first two elements through unconditionally.
  • Failing to generalize: if asked "at most k," the comparison should be with nums[write - k].
  • Overcomplicating with a counter variable instead of using the position-based comparison.

Interview preparation tip

For the Remove Duplicates from Sorted Array II coding problem, think of it as a template: the two-pointer array interview pattern with a configurable "allowed count." Interviewers at TikTok and Adobe often follow up with "what if at most 3 copies were allowed?" — show you can immediately adjust the index offset from 2 to 3. This demonstrates you understand the principle, not just the answer.

Similar Questions