Skip to content
Decoder

Remove Duplicates from Sorted Array II

Medium

Problem

You are given a list nums sorted in non-decreasing order. Remove extra copies in place so that each value appears at most twice, keeping their order. Return k, the length of the result. The first `k` slots of nums must hold it; whatever is after them does not matter.

Example 1

Input
nums = [1, 1, 1, 2, 2, 3]
Output
k = 5, nums starts with [1, 1, 2, 2, 3]

Example 2

Input
nums = [0, 0, 1, 1, 1, 1, 2, 3, 3]
Output
k = 7, nums starts with [0, 0, 1, 1, 2, 3, 3]

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums is sorted in non-decreasing order.
  • Use O(1) extra space.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.