LeetMotion
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place so that each unique element appears only once.
Return k — the number of unique elements. The first k elements of nums should hold the result.
nums is sorted in non-decreasing order.Collect all unique elements into a separate array, then copy them back. This is simple but uses extra space.
nums and collect unique elements into a list.nums in order.Why it's not optimal: Uses O(n) extra space. The two-pointer approach does it truly in-place with O(1) space.
def removeDuplicates(nums): unique = [] for num in nums: if not unique or unique[-1] != num: unique.append(num) for i in range(len(unique)): nums[i] = unique[i] return len(unique)
Use a slow pointer k to track the write position (next slot for a unique element) and a fast pointer i to scan the array. Whenever nums[i] differs from the last unique value written, copy it to position k.
k=1 (first element is always unique) and i=1.nums[i] != nums[k-1], write nums[k] = nums[i] and increment k.i each iteration. Duplicates are simply skipped.k — the count of unique elements.
Discussion
…