Taro Logo

Remove Duplicates from Sorted Array II

#15 Most AskedMedium
0 views
Topics:
ArraysTwo Pointers

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


Clarifying Questions

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:

  1. What should we return if the input array is empty or has a length of less than 3?
  2. Does the order of the elements beyond the returned count matter, or can they be left as garbage values since we are modifying the array in-place?
  3. Can I allocate any extra memory, or are we strictly constrained to $O(1)$ auxiliary space?
  4. Are the elements in the input array guaranteed to be sorted in non-decreasing order?
  5. How should I handle cases where an element already appears three or more times consecutively versus separated throughout the array?

Brute Force Solution

Approach

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:

  1. Start by looking at the very beginning of the row of items.
  2. Pick a subset of items to keep, making sure that no item appears more than two times in a row.
  3. Compare this chosen subset against the rule that allows duplicates up to twice.
  4. If you accidentally included a duplicate a third time, discard this entire combination and try a different grouping.
  5. Write down every valid combination of items that follows the rule of maximum two duplicates.
  6. From all the valid combinations you wrote down, pick the one that keeps the correct amount of items while maintaining the original sorted order.
  7. Finally, present this chosen combination as the final result of cleaned items.

Code Implementation

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 0

Big(O) Analysis

Time Complexity
O(2ⁿ) – The brute force strategy generates all possible subsets of the n elements to test which ones are valid according to the duplicate rule. Since each of the n elements can either be included or excluded independently, there are 2ⁿ possible combinations to check. For each combination, we must scan the subset to verify that no item appears more than twice in a row, taking proportional time. Summing the work across all 2ⁿ subsets results in approximately 2ⁿ operations, which simplifies to the exponential Big O time complexity of O(2ⁿ).
Space Complexity
O(1) – The brute-force and optimal approaches for this problem rely entirely on in-place manipulation of the existing array without allocating any auxiliary data structures. The algorithm only requires a fixed number of pointer variables to track indices and frequencies, regardless of the input size. Since no temporary lists, hash maps, or recursion stacks are created that scale with the input, the extra memory usage remains constant. Therefore, the auxiliary space complexity is O(1) relative to the number of elements N.

Optimal Solution

Approach

The 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:

  1. Look at the first few items of the sorted line, since the very beginning of any sorted group will always follow the repetition rules safely.
  2. Begin moving along the sorted line from left to right to evaluate each subsequent item.
  3. Compare the item you are currently looking at with the item positioned two spots back in your final kept collection.
  4. If the current item is different from that past item, it means we have not exceeded the limit of allowed repetitions.
  5. When the item passes the check, officially add it to your kept collection and make room for the next confirmation.
  6. If the current item is the same as the one from two spots back, skip it entirely because we already have the maximum allowed copies of that item.
  7. Continue this check-and-copy process for every single item until you reach the very end of the line.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – As we move from left to right along the sorted line of size n, a single iterator evaluates each subsequent item exactly once. For every single item, we perform a constant time comparison against the item positioned two spots back in our kept collection. This means the work done per item remains constant as the input grows. The total operations scale directly in proportion to the input size n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm relies entirely on a two-marker strategy operating directly on the original input array without allocating any auxiliary data structures. We only utilize a few constant scalar variables to track our indices as we move from left to right along the sorted line. Consequently, the extra memory used remains completely fixed and independent of the input size N, resulting in constant auxiliary space complexity.

Edge Cases

Empty array or null input
How to Handle:
Check for null or empty array upfront and return zero immediately to avoid null pointer exceptions.
Array with length one or two
How to Handle:
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
How to Handle:
The write pointer correctly stops advancing after the first two occurrences, effectively filtering out all subsequent duplicates.
Array with no duplicates
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The comparison against the element two positions back correctly identifies and drops any excess duplicates regardless of cluster size.
0/16 completed