An interactive visualization of the two-pointer technique for removing duplicates in-place. Watch the slow (write) and fast (scan) pointers work together to compact unique elements to the front of the array.
Two Pointers LeetCode 26 ↗ Easynums sorted in non-decreasing order, remove the duplicates
in-place such that each unique element appears only once. The relative order of the elements should be kept the same.
Then return the number of unique elements.k. You need to place the first k elements
of nums equal to the unique values in order. It does not matter what you leave beyond the first k elements.nums = [0,0,1,1,1,2,2,3,3,4] → return 5, with nums = [0,1,2,3,4,...]
fun removeDuplicates(nums: IntArray): Int { if (nums.size == 0) { return 0 } var slow = 0 for (fast in 1 until nums.size) { if (nums[fast] != nums[slow]) { // new unique slow++ nums[slow] = nums[fast] } // copy } return slow + 1 } // count of unique
Because the array is already sorted, all duplicates are adjacent. We only need one pass
with two pointers: a slow pointer tracking where to write the next unique value, and a
fast pointer scanning ahead to find it. When nums[fast] != nums[slow], we
have found a new unique element and copy it forward.
slow = 0 (the first element is always unique).fast iterates from index 1 to the end.nums[fast] != nums[slow], we found a new unique value.slow, then copy nums[fast] into nums[slow].nums[fast] == nums[slow], it is a duplicate — just advance fast.slow + 1 — the count of unique elements now in nums[0..slow].The fast pointer visits each element exactly once, and each write operation is O(1). No extra data structures are needed — everything happens in-place.