algoadvance

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.

Example 1:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Function should return the new length, which is 2, and the first two elements of nums being modified to 1 and 2 respectively. It does not matter what is left beyond the new length.

Example 2:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Function should return the new length, which is 5, and the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It does not matter what is left beyond the new length.

Clarifying Questions

  1. Q: Can the input array be empty? A: Yes, the input array can be empty. If the array is empty, the return value should be 0.

  2. Q: Should the function handle negative numbers? A: Yes, the function should handle both positive and negative numbers since the array is sorted.

  3. Q: Does the order of elements matter after removing duplicates? A: Yes, the order should be maintained as it is in the sorted array.

Strategy

Since the array is sorted, all duplicates are adjacent. We can use the two-pointer technique where one pointer i tracks the place for the next unique element, and another pointer j scans through the array to find the next unique element.

Code

def removeDuplicates(nums):
    if not nums:
        return 0

    # Initialize the first pointer
    i = 0
    for j in range(1, len(nums)):
        if nums[j] != nums[i]:
            i += 1
            nums[i] = nums[j]

    return i + 1

# Example usage:
nums = [0,0,1,1,1,2,2,3,3,4]
length = removeDuplicates(nums)
print(length)  # Output: 5
print(nums[:length])  # Output: [0, 1, 2, 3, 4]

Time Complexity

This solution effectively removes duplicates in-place with minimal extra memory and maintains the order of the array.

Try our interview co-pilot at AlgoAdvance.com