Allow at Most Two of Each Sorted Value

medium array two pointers in-place

Problem

A sorted array may contain runs of the same value. Compact it in place so each value appears at most twice, preserving order, and return the new length. The clean trick: a write index w. Copy the next read value if either fewer than two slots are filled, or the value sitting two positions back at nums[w-2] is different. Because the array is sorted, all duplicates of a value sit in a single run, so checking just two back is enough.

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)