Given a sorted array nums, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Your function should return the new length k after removing the duplicates. Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.
Constraints:
0 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 100numsis sorted in non-decreasing order.
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 represented by 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.
Solution
Approach: This problem can be efficiently solved using a two-pointer technique.
- One pointer (
j) keeps track of the position where the next unique element should be placed. - Another pointer (
i) iterates through the array to find new unique elements.
- One pointer (
Steps:
- Handle the edge case: If the array is empty, return
0. - Initialize
j = 1. This pointer will point to the second position where a unique element might be written (the first elementnums[0]is always considered unique in a non-empty array). - Iterate
ifrom1tolen(nums) - 1(starting from the second element). - At each
i, comparenums[i]with the previous elementnums[i-1]. - If
nums[i]is different fromnums[i-1], it means we've found a new unique element.- Place this unique element at
nums[j]. - Increment
jto prepare for the next unique element.
- Place this unique element at
- After the loop finishes,
jwill represent the count of unique elements, which is also the new length of the modified array.
- Handle the edge case: If the array is empty, return
Code (Python):
class Solution: def removeDuplicates(self, nums: list[int]) -> int: if not nums: return 0 # Pointer `j` marks the position for the next unique element. # The first element (at index 0) is always unique, so we start `j` at 1. j = 1 # Pointer `i` iterates through the array starting from the second element. for i in range(1, len(nums)): # If the current element `nums[i]` is different from the element just before it `nums[i-1]`, # it means `nums[i]` is a new unique element. if nums[i] != nums[i-1]: # Place this unique element at the position `j`. nums[j] = nums[i] # Move `j` to the next available position for a unique element. j += 1 # The value of `j` at the end represents the new length of the array # with duplicates removed (and also the count of unique elements). return j
