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.\n\n* Do not allocate extra space for another array.\n* Modify the input array nums in-place with O(1) extra memory.\n* The function should return the new length of the array.\n\n\nInput: nums = [1,1,2]\nOutput: 2, nums = [1,2,_]\nExplanation: Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.\n\n\n\nInput: nums = [0,0,1,1,1,2,2,3,3,4]\nOutput: 5, nums = [0,1,2,3,4,_,_,_,_,_]\nExplanation: Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.\n
Solution
Approach: Use two pointers.\n\n* One pointer, i (or slow), tracks the position where the next unique element should be placed. It starts at index 0.\n* Another pointer, j (or fast), iterates through the array from index 1 to find unique elements.\n* If nums[j] is different from nums[i], increment i, then copy nums[j] to nums[i]\n* If nums[j] is the same as nums[i], it's a duplicate; increment j to skip it.\n* The final length is i + 1.\n\npython\nclass Solution:\n def removeDuplicates(self, nums: list[int]) -> int:\n if not nums:\n return 0\n\n i = 0 # Pointer for the unique elements\n for j in range(1, len(nums)): # Pointer to iterate through the array\n if nums[j] != nums[i]:\n i += 1\n nums[i] = nums[j]\n return i + 1\n