# 1. Introduction

In this blog post, we will solve the problem of removing duplicates from a sorted array. Unlike the traditional problem where each element can only appear once, in this variant, each element is allowed to appear at most twice.

## Problem

Given a sorted array, remove the duplicates such that each element can appear at most twice, and return the new length. The operation must be done in place with O(1) extra memory.

Example:

Given array [1, 1, 1, 3, 5, 5, 7]

The output should be 6, with the first six elements of the array being [1, 1, 3, 5, 5, 7]

# 2. Solution Steps

1. Initialize a counter (count) to track the number of times a particular element has appeared.

2. Initialize a pointer (index) to track the position in the array where the next unique element should be placed.

3. Iterate through the array, starting from the first element.

4. For each element, increment count if it's the same as the previous one; otherwise, reset count to 1.

5. If count is less than or equal to 2, update the array at index with the current element and increment index.

6. Continue this process until the end of the array.

7. Return index as the new length of the array.

# 3. Code Program

``````public class Solution {

// Main method for testing
public static void main(String[] args) {
int[] nums = {1, 1, 1, 3, 5, 5, 7};
int newLength = removeDuplicates(nums);
System.out.println("New length: " + newLength);
for (int i = 0; i < newLength; i++) {
System.out.print(nums[i] + " ");
}
}

// Method to remove duplicates such that each element appears at most twice
public static int removeDuplicates(int[] nums) {
if (nums.length <= 2) return nums.length;

int index = 1; // Start from the second element
int count = 1;

for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1]) {
count++;
} else {
count = 1;
}

if (count <= 2) {
nums[index] = nums[i]; // Update the array with the element
index++;
}
}
return index; // New length of the array
}
}
``````

### Output:

```New length: 6
1 1 3 5 5 7
```

### Explanation:

In the given array [1, 1, 1, 3, 5, 5, 7], the removeDuplicates method allows each unique element to appear at most twice. It iterates through the array, counting the occurrences of each element and updating the array in-place. The new length of the array is 6, representing the elements [1, 1, 3, 5, 5, 7], where each element appears no more than twice.