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] <= 104nums is sorted in non-decreasing order.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a long row of sorted items where some items repeat too many times and you only want to allow any item to repeat up to twice. The brute force approach involves looking at every possible combination of keeping and throwing away items to see what the final cleaned-up row would look like.
Here's how the algorithm would work step-by-step:
def remove_duplicates(sorted_numbers):
from itertools import combinations
# Generate all possible subsequences to evaluate every combination of items
for total_length in range(len(sorted_numbers), -1, -1):
for current_combination in combinations(sorted_numbers, total_length):
is_valid_sequence = True
for index_position in range(2, len(current_combination)):
if current_combination[index_position] == current_combination[index_position - 2]:
is_valid_sequence = False
break
# Filter combinations to strictly enforce the maximum two duplicates rule
if is_valid_sequence:
for target_index in range(len(current_combination)):
sorted_numbers[target_index] = current_combination[target_index]
return len(current_combination)
return 0The optimal approach uses a two-marker strategy to inspect items one by one and selectively copy only the allowed elements into a forming sequence. By comparing each new item against items already confirmed for the final result, we can filter out excessive duplicates instantly without needing extra storage space.
Here's how the algorithm would work step-by-step:
def remove_duplicates(sorted_numbers):
if len(sorted_numbers) <= 2:
return len(sorted_numbers)
# The first two elements are always safe to keep since duplicates up to two are allowed.
insert_position = 2
for current_index in range(2, len(sorted_numbers)):
# Comparing with the element two spots back ensures we allow at most two duplicates.
if sorted_numbers[current_index] != sorted_numbers[insert_position - 2]:
sorted_numbers[insert_position] = sorted_numbers[current_index]
insert_position += 1
# The insert position directly represents the new valid length of the modified array.
return insert_position| Case | How to Handle |
|---|---|
| Empty array or null input | Check for null or empty array upfront and return zero immediately to avoid null pointer exceptions. |
| Array with length one or two | The two-pointer approach naturally skips modification and returns the array length directly since duplicates cannot exceed the limit of two. |
| Array with all identical elements | The write pointer correctly stops advancing after the first two occurrences, effectively filtering out all subsequent duplicates. |
| Array with no duplicates | The read and write pointers will move in lockstep, leaving the entire array completely unmodified and returning its original length. |
| Array with exactly two of each element mixed throughout | Every element pair is allowed by the two-occurrence constraint, so the array remains unchanged and the full length is returned. |
| Negative numbers and extreme boundary values | Since the algorithm only compares adjacent values using index offsets rather than absolute values, it handles negative integers and boundary limits seamlessly. |
| Maximum-sized inputs | Operating with an in-place O(1) space complexity and O(N) time complexity ensures the solution scales efficiently without memory overhead. |
| Highly skewed distributions with clusters of many duplicates | The comparison against the element two positions back correctly identifies and drops any excess duplicates regardless of cluster size. |