{x}
blog image

Remove Duplicates from Sorted Array II

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.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.

Custom Judge:

The judge will test your solution with the following code:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}

If all assertions pass, then your solution will be accepted.

 

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 * 104
  • -104 <= nums[i] <= 104
  • nums is sorted in non-decreasing order.

Solution Explanation for Remove Duplicates from Sorted Array II

This problem requires removing duplicates from a sorted array while ensuring each unique element appears at most twice. The solution must be in-place, meaning it should modify the input array directly without using extra space proportional to the input size (O(1) extra space).

Approach: Two Pointers (Single Pass)

The most efficient approach uses a single pass through the array with two pointers:

  1. k (write pointer): This pointer keeps track of the index where the next unique element (or its second occurrence) should be written. It represents the current length of the processed array.

  2. Implicit read pointer (loop index): The loop implicitly iterates through the array, serving as a read pointer.

The algorithm works as follows:

  • Initialize k to 0.
  • Iterate through the array using a for loop (or equivalent).
  • For each element x:
    • If k < 2 (meaning we haven't placed two occurrences of any element yet) or x is different from the element at nums[k-2] (meaning it's a new unique element or we can add another occurrence of the current unique element), then:
      • Write x to nums[k].
      • Increment k.
    • Otherwise, skip x because it's a duplicate that exceeds the allowed limit.
  • Return k, which is the length of the modified array.

Time and Space Complexity

  • Time Complexity: O(n), where n is the length of the input array. We perform a single pass through the array.
  • Space Complexity: O(1). The algorithm uses only a constant amount of extra space to store the k variable.

Code Examples (Multiple Languages)

The following code examples demonstrate the solution in various programming languages. Note the similarities in the core logic across all examples:

Python

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 0
        for x in nums:
            if k < 2 or x != nums[k - 2]:
                nums[k] = x
                k += 1
        return k
 

Java

class Solution {
    public int removeDuplicates(int[] nums) {
        int k = 0;
        for (int x : nums) {
            if (k < 2 || x != nums[k - 2]) {
                nums[k++] = x;
            }
        }
        return k;
    }
}

C++

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int k = 0;
        for (int x : nums) {
            if (k < 2 || x != nums[k - 2]) {
                nums[k++] = x;
            }
        }
        return k;
    }
};

JavaScript

var removeDuplicates = function(nums) {
    let k = 0;
    for (let x of nums) {
        if (k < 2 || x != nums[k - 2]) {
            nums[k++] = x;
        }
    }
    return k;
};

Go

func removeDuplicates(nums []int) int {
	k := 0
	for _, x := range nums {
		if k < 2 || x != nums[k-2] {
			nums[k] = x
			k++
		}
	}
	return k
}

These examples all follow the same fundamental approach, differing only in syntax. The key is the efficient use of a single k pointer to manage the in-place modification and tracking of the new array length.