Pattern visualizer
Remove Duplicates from Sorted Array
The key insight: use a slow pointer to mark the position of the last unique element written, and a fast pointer to scan through the array. Since the array is sorted, duplicates appear consecutively. When nums[fast] != nums[slow], we've found a new unique element: advance slow and write nums[fast] there. All elements beyond slow are irrelevant after the process completes. Animated on: Given nums = [1, 1, 2, 2, 3], remove duplicates in-place such that the first k elements are unique. Return k = 3, and the first 3 elements become [1, 2, 3]..
Two Pointers
slow = 0, fast = 1: initialize the slow pointer at the first element (it's always unique so far) and fast at the second element; we're scanning to find the next unique value.
1FUNCTION removeDuplicates(nums):2 IF n = 0: RETURN 03 slow = 04 FOR fast from 1 to n-1:5 IF nums[fast] != nums[slow]:6 slow = slow + 17 nums[slow] = nums[fast]
← / → step · space play · Home restart