Fast and slow pointers
After this: Remove repeats in place with a read pointer and a write pointer.
On this page · 7 sections · 3 checks
In the last lesson, two pointers started at the two ends and moved towards each other. In this lesson both pointers start near the front and move in the same direction, but one moves more often than the other.
Here is the job. A sorted array has some repeated values: [1, 1, 2, 3, 3]. You want each value once: 1, 2 and 3.
There are two ordinary ways to do this, and each has a cost.
- Delete each repeat. Every cell after the repeat has to move one place left, as you saw in Inserting and deleting. That is O(n) for one delete, which means that the work grows with the size of the array, and there may be many repeats to delete.
- Build a second array. This works, but it needs extra memory for up to n more values.
This lesson does neither. It changes the array itself, and it uses only two extra variables. Working this way is called working .
A reader and a writer
Imagine two people working along a row of boxes.
- The reader walks along the row and looks at every box.
- The writer stands at the next place to fill.
When the reader finds a value that has not been kept yet, the writer puts a copy of it in their place and takes one step forward. When the reader finds a repeat, the writer stands still.
In code, these two people are two pointers, read and write. Moving the good values to the front in this way is called the array.
Step by step
Take [1, 1, 2, 3, 3]. The first value can never be a repeat, so it is always kept. That is why write starts at index 1, and so does read. The last kept value is always in the cell right before write.
readis at index 1, which holds 1. The last kept value is 1. This is a repeat, so onlyreadmoves.readis at index 2, which holds 2. The last kept value is 1. This is a new value, so write 2 at index 1. The array is now[1, 2, 2, 3, 3], andwritemoves to 2.readis at index 3, which holds 3. The last kept value is 2. This is a new value, so write 3 at index 2. The array is now[1, 2, 3, 3, 3], andwritemoves to 3.readis at index 4, which holds 3. The last kept value is 3. This is a repeat, so onlyreadmoves.
read has reached the end. write is 3, so three values were kept, and they are the first three cells: 1, 2 and 3.
read moves at every step, so it is the fast pointer. write moves only when a value is kept, so it is the slow pointer. This only works on a sorted array, because sorting puts equal values next to each other, so a repeat always matches the last kept value.
The rule
At every step, one fact stays true: everything before write is the answer so far. Those cells have no repeats, they are in order, and they will not change again. This is the invariant of this pass, the fact that stays true at every step of the loop.
There is also a reason why no value is lost. write can never get ahead of read, so we never write over a cell that read has not looked at yet.
The code
def compact(nums): if len(nums) == 0: return 0 write = 1 # index 0 is always kept for read in range(1, len(nums)): # read visits every cell once if nums[read] != nums[write - 1]: # a new value: keep it nums[write] = nums[read] write += 1 return write # the first write cells are the kept values
nums = [1, 1, 2, 3, 3]n = compact(nums)print(n, nums)3 [1, 2, 3, 3, 3]
import java.util.Arrays;
public class Main { static int compact(int[] nums) { if (nums.length == 0) return 0; int write = 1; // index 0 is always kept for (int read = 1; read < nums.length; read++) { // read visits every cell once if (nums[read] != nums[write - 1]) { // a new value: keep it nums[write] = nums[read]; write++; } } return write; // the first write cells are the kept values }
public static void main(String[] args) { int[] nums = {1, 1, 2, 3, 3}; int n = compact(nums); System.out.println(n + " " + Arrays.toString(nums)); }}3 [1, 2, 3, 3, 3]
Here is how to read it.
- An empty array has nothing to keep, so the function returns 0.
writestarts at 1, because index 0 is always kept.- The loop moves
readthrough every cell from index 1 to the end. nums[write - 1]is the last kept value. If the value atreadis different, it is new, so it is copied towriteandwritemoves on.
The function returns 3, and the array is [1, 2, 3, 3, 3]. The answer is the first three cells. The last two cells are leftovers from the original array, because the pass never clears them. The array did not get shorter. That is why the function returns the new length: it tells you how many cells to trust.
read goes through the array once, and each step does one comparison and at most one write. So the cost is O(n).
Watch it happen
The task asks you to tap a cell before it starts. Tap the cell where you think write will stop.
- Compact duplicatesread goes through indexes 1 to 4. write moves only when a new value is kept.
- 01
- 11
- 22
- 33
- 43
Run an operation to begin.
That took four comparisons and two writes, and nothing was shifted. When the pass ends, the visualizer empties the leftover cells so that you can see the new size. The real code leaves them as they are.
Check yourself
At every moment of the pass, what is true of the cells before write?
What does this print?
def compact(nums): if len(nums) == 0: return 0 write = 1 # index 0 is always kept for read in range(1, len(nums)): # read visits every cell once if nums[read] != nums[write - 1]: # a new value: keep it nums[write] = nums[read] write += 1 return write # the first write cells are the kept values
nums = [1, 1, 2, 3, 3]n = compact(nums)print(n, nums)import java.util.Arrays;
public class Main { static int compact(int[] nums) { if (nums.length == 0) return 0; int write = 1; // index 0 is always kept for (int read = 1; read < nums.length; read++) { // read visits every cell once if (nums[read] != nums[write - 1]) { // a new value: keep it nums[write] = nums[read]; write++; } } return write; // the first write cells are the kept values }
public static void main(String[] args) { int[] nums = {1, 1, 2, 3, 3}; int n = compact(nums); System.out.println(n + " " + Arrays.toString(nums)); }}Compact [4, 4, 4, 7, 9, 9]. Right after read has dealt with index 3, where is write and what does the row hold?
Connect
- Compact a sorted array in place, with a read pointer that visits every cell and a write pointer that moves only when a value is kept.
- State the invariant: everything before write is the answer so far, with no repeats and in order.
- Explain that the function returns the new length, and that the end of the array still holds leftovers.