Remove Duplicates from Sorted Array II

Medium#80same direction

You get an array of numbers sorted from smallest to largest. Rewrite it in place so that every number appears at most twice, keeping the order, and return how many numbers are left; whatever lies after them does not matter. Our example: [1, 1, 1, 2, 2, 3, 3, 3, 3] → 6, and the array starts with [1, 1, 2, 2, 3, 3].

input
nums: integers in non-decreasing order, so equal ones stand together.
returns
k, how many numbers stay when each number is kept at most twice. Change nums in place so that its first k items are those numbers, in their order; what is left after them does not matter.
constraints
  • 1 ≤ nums.length ≤ 3 · 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • nums is in non-decreasing order
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @return {number}
 */
function removeDuplicates(nums) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more two pointers problems

Pattern “Two pointers” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.