Problem Description
Given a sorted integer array, remove the duplicates in-place such that each unique element appears only once. The relative order must be maintained. Return the number of unique elements (k) with the guarantee that the first k elements in the array contain the unique elements.
Key Insights
- The array is sorted in non-decreasing order, meaning duplicate values appear consecutively.
- Use a two-pointer approach:
- One pointer to iterate through the array.
- Another pointer to track the position to place the next unique element.
- The solution modifies the array in place with O(1) extra space.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the input array.
Space Complexity: O(1) since the modification is done in-place.
Solution
The approach uses two pointers. The first pointer (uniqueIndex) tracks the position for the next unique element, starting from index 1. The second pointer iterates over the array from index 1 to the end. Whenever a new element (different from the previous element) is encountered, it is placed at uniqueIndex, and uniqueIndex is incremented. Finally, uniqueIndex represents the count of unique elements and denotes how many elements are valid in the modified array.