Remove Duplicates from Sorted Array II

medium array two pointers in-place

Problem

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.

Inputnums = [1, 1, 1, 2, 2, 3]
Output5, nums starting [1, 1, 2, 2, 3, …]
Two 1's, two 2's, and one 3 survive. The third 1 is dropped because nums[w-2] is already 1.

def remove_duplicates(nums):
    w = 0
    for x in nums:
        if w < 2 or x != nums[w - 2]:
            nums[w] = x
            w += 1
    return w
function removeDuplicates(nums) {
  let w = 0;
  for (const x of nums) {
    if (w < 2 || x !== nums[w - 2]) {
      nums[w++] = x;
    }
  }
  return w;
}
class Solution {
    public int removeDuplicates(int[] nums) {
        int w = 0;
        for (int x : nums) {
            if (w < 2 || x != nums[w - 2]) {
                nums[w++] = x;
            }
        }
        return w;
    }
}
int removeDuplicates(vector<int>& nums) {
    int w = 0;
    for (int x : nums) {
        if (w < 2 || x != nums[w - 2]) {
            nums[w++] = x;
        }
    }
    return w;
}
Time: O(n) Space: O(1)