Taro Logo

Remove Duplicates from Sorted Array

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+17
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.6K views
Topics:
ArraysTwo Pointers

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

  • Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
  • Return k.

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,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 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,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Constraints:

  • 1 <= nums.length <= 3 * 104
  • -100 <= nums[i] <= 100
  • 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 null?
  2. Does 'modify the array in-place' mean we need to return the modified array itself, or just the integer count of unique elements while modifying the prefix of the array?
  3. What happens to the elements in the array beyond the new length of unique elements? Do they need to be cleared/ignored, or can they retain their original values?
  4. Can we assume the input array is already sorted in non-decreasing order as stated, or should we validate this?
  5. What are the constraints on the array size ($N$) and the integer values themselves (e.g., fit within standard 32-bit signed integers)?

Brute Force Solution

Approach

Imagine you have a line of items already arranged in order, and you want to clean it up by throwing away any exact duplicates so that every item is unique. The brute force approach involves looking at every single pair of items one by one to see if they match.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item in the line.
  2. Compare this first item with every other item that comes after it to check for matches.
  3. If you find a match later in the line, mark that duplicate item to be removed.
  4. Then, move to the second item and compare it with all the items that follow it, marking any duplicates you find.
  5. Repeat this thorough checking process for every single item until you have compared every possible pair.
  6. Finally, gather all the items that were not marked as duplicates and place them into a fresh, clean line while keeping their original order.

Code Implementation

def remove_duplicates(sorted_numbers):
    marked_indices = set()

    # Compare every possible pair to find duplicates since brute force requires exhaustive checks
    for current_index in range(len(sorted_numbers)):
        if current_index in marked_indices:
            continue

        for comparison_index in range(current_index + 1, len(sorted_numbers)):
            if sorted_numbers[current_index] == sorted_numbers[comparison_index]:
                marked_indices.add(comparison_index)

    clean_collection = []

    # Collect only unmarked items to build a duplicate-free list in the original order
    for index_position in range(len(sorted_numbers)):
        if index_position not in marked_indices:
            clean_collection.append(sorted_numbers[index_position])

    # Mutate the input array in place to meet the standard problem signature requirement
    for final_index in range(len(clean_collection)):
        sorted_numbers[final_index] = clean_collection[final_index]

    return len(clean_collection)

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in the sorted array, we compare it against every subsequent item in the line to check for matches. The first item requires checking n minus 1 elements, the second item requires n minus 2 checks, and this process continues until all pairs are evaluated. This nested comparison of every possible pair results in approximately n times n over 2 total operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute force approach described in the plain English explanation gathers all unique items into a fresh, clean line or new list, which requires allocating an auxiliary array to store up to N elements. However, in an optimal in-place solution for this problem, we only use a few constant pointers and integer variables to keep track of indices. Assuming we evaluate the auxiliary memory based on the final gathering step explicitly mentioned in the text, it utilizes an extra array of size N. Therefore, depending on whether the algorithm strictly follows the text's fresh line creation or modifies the array in place, the auxiliary space complexity ranges from O(1) for in-place modification to O(N) for storing the newly gathered unique items.

Optimal Solution

Approach

The optimal approach uses a tracking method to rewrite the line of items in place, keeping only the unique ones at the front. By having one person scan through all the items and another person mark where the next unique item should go, we avoid needing extra space or doing messy shuffling.

Here's how the algorithm would work step-by-step:

  1. Look at the very first item in the line, since the first item is always unique by default.
  2. Designate a spot right after the first item to receive the next new discovery.
  3. Walk down the line item by item to inspect what is there.
  4. Whenever you spot an item that is different from the one before it, pick it up.
  5. Move that new item to the designated spot and advance the spot forward by one step.
  6. Continue walking down the line until every single item has been inspected and the unique ones are neatly gathered at the front.

Code Implementation

def remove_duplicates(sorted_numbers_list):
    if not sorted_numbers_list:
        return 0

    # The first item is always unique, so the insertion spot starts right after it.
    next_unique_spot = 1

    for current_index in range(1, len(sorted_numbers_list)):
        # We only care when a new item differs from its predecessor to filter duplicates.
        if sorted_numbers_list[current_index] != sorted_numbers_list[current_index - 1]:
            sorted_numbers_list[next_unique_spot] = sorted_numbers_list[current_index]
            next_unique_spot += 1

    # We return the count of unique elements, which matches the final insertion index.
    return next_unique_spot

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of items in the sorted array that need to be processed. As we walk down the line item by item in a single pass, our scanning pointer inspects each element exactly once. The designated insertion pointer also moves at most n times as it tracks the unique items found. This linear progression means the total operations scale directly with n, which simplifies to O(n).
Space Complexity
O(1) – The algorithm uses a tracking method to rewrite items in place without utilizing any extra data structures like temporary lists or hash maps. Only a fixed number of pointer variables are employed to scan the input array and mark positions, regardless of how large the input array size N grows. Therefore, the auxiliary space remains constant, perfectly matching the requirement to modify the input array in place.

Edge Cases

Empty array or null input
How to Handle:
Return zero immediately as there are no elements to process.
Array with a single element
How to Handle:
Return one since a single element is already unique by definition.
Array with all identical elements
How to Handle:
The slow pointer stays at index zero while the fast pointer scans through, resulting in a length of one.
Array with no duplicates
How to Handle:
Both pointers move synchronously through the array, returning the original length unchanged.
Array containing negative numbers and zeros
How to Handle:
Value comparisons work identically for negative numbers and zeros since the array is already sorted numerically.
Extremely large arrays nearing memory or time limits
How to Handle:
An O(N) time and O(1) space two-pointer approach processes the array in a single pass without exceeding constraints.
Array with alternating duplicates and unique values
How to Handle:
The write pointer correctly selectively updates elements in-place to compress the sequence while preserving relative order.
0/75 completed