Remove Duplicates from Sorted Array
Given a sorted array, the task is to remove the duplicate elements in-place such that each unique element appears only once. The relative order of the elements should be preserved. This is a common problem in data processing and algorithm optimization where reducing data redundancy is crucial for efficiency.
Problem Description
You are provided with an integer array nums that is sorted in non-decreasing order. Your goal is to modify the array in-place such that all duplicate elements are removed, and each unique element appears only once. The modified array should still be sorted.
The function you implement should return the new length of the array after removing duplicates. The elements beyond this new length do not matter.
Key Requirements:
- Modify the input array
numsdirectly (in-place). - Preserve the relative order of the unique elements.
- Return the number of unique elements (the new length).
Expected Behavior:
If nums = [1, 1, 2], after the operation, the first two elements of nums should be [1, 2]. The function should return 2.
If nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4], after the operation, the first five elements of nums should be [0, 1, 2, 3, 4]. The function should return 5.
Edge Cases to Consider:
- An empty array.
- An array with only one element.
- An array where all elements are duplicates.
- An array with no duplicate elements.
Examples
Example 1:
Input: nums = [1, 1, 2]
Output: 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).
nums = [1, 2, _]
Example 2:
Input: nums = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: 5
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.
nums = [0, 1, 2, 3, 4, _, _, _, _, _]
Example 3:
Input: nums = [5, 5, 5, 5, 5]
Output: 1
Explanation: The array should become [5, _, _, _, _] and the function should return 1.
Example 4:
Input: nums = [1, 2, 3, 4, 5]
Output: 5
Explanation: No duplicates, so the array remains unchanged and the function returns 5.
nums = [1, 2, 3, 4, 5]
Constraints
0 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100numsis sorted in non-decreasing order.- The solution should have a time complexity of O(n), where n is the length of the array.
- The solution should use O(1) extra space (in-place modification).
Notes
- You are modifying the input array directly. The values beyond the returned length are irrelevant.
- Consider using a two-pointer approach. One pointer can keep track of the position for the next unique element, and another can iterate through the array.
- Think about how to efficiently compare adjacent elements to identify duplicates.