Use two pointers (write and read). Allow at most 2 duplicate occurrences by comparing current element with write-2 index before writing.
class Solution:
def removeDuplicates(self, nums: list[int]) -> int:
if len(nums) <= 2: return len(nums)
l, r = 2, 2
while r < len(nums):
if nums[r] != nums[l - 2]:
nums[l] = nums[r]
l += 1
r += 1
return l
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length <= 2) return nums.length;
int l = 2;
for (int r = 2; r < nums.length; r++) {
if (nums[r] != nums[l - 2]) {
nums[l++] = nums[r];
}
}
return l;
}
}