## 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.

#### Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

## Solution

## Explanation

You have to return `length`

of the new array. But, because the array itself is passed by reference the caller knows the new values.

Because we have to sort the array - time complexity would at least be `O(n)`

We can maintain three pointers

- i -> pointing to the first instance of the unique element
- j -> pointing to the second instance of the unique element
- k -> pointing to the current element being inspected

And finally return `j+1`

Relation between `i`

and `j`

is that they will either be equal or `j`

will be 1 place ahead of `i`

This constraint will help us make sure that there are at most 2 instances of the given element

As soon as `k`

finds the third instance - we will simply continue without doing anything
Something like this:

## Sample test cases

## Highlights

**Runtime:** 88 ms, faster than 68.14% of JavaScript online submissions for Remove Duplicates from Sorted Array II.

**Memory Usage:** 38.6 MB, less than 64.88% of JavaScript online submissions for Remove Duplicates from Sorted Array II.

### Disclaimer

This may not be the optimal solution. And that’s okay. The purpose here is to practice problem solving and have fun with algorithms. I am constantly learning new optimized solutions for these problems.

Please comment below if you have a better solution. Let’s learn algorithms and data structures together.