Remove Duplicates from Sorted Array II

MediumTwo Pointerstwo pointers

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array nums sorted in non-decreasing order. Rewrite it **in place** so that every distinct value appears at most twice, keeping the relative order of the elements. Use O(1) extra memory. Let k be the number of elements that remain. The first k slots of nums must hold the kept elements; anything after them does not matter. For grading, return the list of those first k elements (for example nums[:k]). Values that appear once stay once; values that appear three or more times are cut down to two copies.

Examples

Input: nums = [1,1,1,2,2,3]
Output: [1,1,2,2,3]
The third 1 is removed; 2 and 3 are already within the limit.
Input: nums = [0,0,1,1,1,1,2,3,3]
Output: [0,0,1,1,2,3,3]
Two of the four 1s are removed.

Constraints

  • 0 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • `nums` is sorted in non-decreasing order.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More two pointers problems