---
title: '80. Remove Duplicates from Sorted Array II'
description: Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same
icon: dot
topics:
  - { name: "Array", slug: "array" }
  - { name: "Two Pointers", slug: "two-pointers" }
issue: "https://github.com/prdlk/leetcode/issues/48"
sidebar:
  label: 'Remove Duplicates from Sorted Array II'
  badge: 'Medium'
---

### Example 1:
- Input: `nums = [1,1,1,2,2,3]`
- Output: `5, nums = [1,1,2,2,3,_]`
- Explanation: Your function should return `k = 5`, with the first five elements of `nums` being `1`, `1`, `2`, `2` and `3` respectively. It does not matter what you leave beyond the returned `k` (hence they are underscores).

### Example 2:
- Input: `nums = [0,0,1,1,1,1,2,3,3]`
- Output: `7, nums = [0,0,1,1,2,3,3,_,_]`
- Explanation: Your function should return `k = 7`, with the first seven elements of `nums` being `0`, `0`, `1`, `1`, `2`, `3` and `3` respectively. It does not matter what you leave beyond the returned `k` (hence they are underscores).

### Constraints:

- `1 <= nums.length <= 3 * 10^4`
- `-10^4 <= nums[i] <= 10^4`
- `nums` is sorted in non-decreasing order.

## Solution

```py
class Solution:
    def removeDuplicates(self, nums: list[int]) -> int:
        slow = 0
        for fast in range(len(nums)):
            if slow < 2 or nums[fast] != nums[slow - 2]:
                nums[slow] = nums[fast]
                slow += 1
        return slow
```
