Lesson 2 of 3
Fast and slow pointers
Two pointers can walk one linked list at different speeds, or at the same speed with a fixed gap between them. That finds the middle in one walk, catches a list that loops forever, and finds the n-th node from the end, all with O(1) extra space.
Trace
slowandfastthrough a linked list and say where each one stops on odd and even lengthsWrite a loop condition that never reads
.nextfromNoneDetect a cycle with two speeds and explain why the fast pointer cannot jump over the slow one
Find and remove the n-th node from the end in one walk, with a gap of n and a dummy head
Say the brute force, the promise and the cost of each of the three walks
Here is a linked list of five nodes: 8 → 3 → 5 → 2 → 7. Which node is in the middle? With a Python list you would compute len(nums) // 2 and jump straight there. A linked list has no length to read and no way to jump. All you hold is head, the first node. As in the previous lesson, each node is a ListNode with a value, node.val, and a link to the node after it, node.next, which is None after the last node. The only move is one node forward: cur = cur.next.
The plain answer is to walk twice: once to count the nodes, then again to stop halfway. That works, and it costs O(n) time, work that grows in step with the number of nodes, n. But counting fails on one kind of list: if a node links back to an earlier node, the counting walk never ends.
This lesson's tool is two pointers on one list: at two speeds, or at one speed with a fixed gap. A pointer here is a name that points at a node, the way cur did in the previous lesson. (In module 4 a pointer was an index into a list; here it is the node itself.) Three classic problems fall to it: the middle node, a list that loops forever, and the n-th node from the end. Each keeps a few names, however long the list, so O(1) extra space.
Two speeds find the middle
How can one walk find the middle without knowing the length? Send two walkers from the head. Each step, slow moves one node and fast moves two. In code, one step is one pass of a loop. Positions count from 0, as in a Python list. After k steps, slow is at position k and fast is at position 2k. When fast reaches the end, slow has gone half as far: the middle.
The trace runs this on 8 → 3 → 5 → 2 → 7. The state panel draws the nodes as a chain, and above each node a tag names every pointer that refers to it. Before you step through, guess which value it prints.
head = build_list([8, 3, 5, 2, 7])slow = headfast = headwhile fast is not None and fast.next is not None:slow = slow.nextfast = fast.next.nextprint(slow.val)
(nothing printed yet)Where fast stops depends on the length. With five nodes, fast lands on the last node, where fast.next is None, so it cannot move two more nodes. With an even length, its last move carries it one node past the end, onto None itself. Either way slow stops at position n // 2 (// divides and drops the remainder). Here that is 5 // 2 = 2, the node holding 5. An even length has two middle nodes, and position n // 2 is the second of them. Predict the even case.
This is the loop from the trace, run on four nodes, with a print at the end of each pass. Type exactly what it prints, one value per line.
head = build_list([6, 1, 9, 4])
slow = head
fast = head
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
print(slow.val)
print(fast)
The loop condition has two parts, and their order matters. fast.next.next reads next twice, so both fast and fast.next must be real nodes. Reading .next from None raises an error (an AttributeError). Python's and checks its left side first and stops there if it is false, so in fast is not None and fast.next is not None, the right side is never read when fast is None.
Four people wrote the middle loop with different conditions. The body is the same in each:
while CONDITION:
slow = slow.next
fast = fast.next.next
Which condition works on every list of one or more nodes, odd or even length?
Choose one answer, then check.
Now write it from a blank editor. The problem wants the node itself, so return slow, not its value.
The solution is the loop you traced, inside a function. One node needs no extra code: fast.next is None at once, the loop never runs, and the head comes back. The problem's written solution opens with the two-pass version on purpose: counting first is a correct O(n) answer, and naming it first is part of a good plan. Fast and slow is not faster in Big O: both versions follow about 1.5n links. It buys one walk instead of two, and a tool that still works where counting never finishes.
Interviewers often change a known problem instead of repeating it. A small change tests whether you own the loop condition: return the first of the two middles. On [6, 1, 9, 4] that is the 1. Stop fast one step earlier: move only while fast.next and fast.next.next are both nodes. Reorder List, in this module's practice bank, starts with this loop.
Put the lines in order to build first_middle(head), which returns the middle node of a list with at least one node, and the first of the two middles when the length is even: on [6, 1, 9, 4] it returns the node holding 1. Indentation is part of each line. Two lines do not belong.
slow, fast = slow.next, fast.next.next moves both walkers in one line: Python computes both values on the right first, then points the names on the left at them.
Add lines from the list below, in order.
def first_middle(head):return slowslow, fast = slow.next, fast.nextslow, fast = head, headslow, fast = slow.next, fast.next.nextwhile fast.next is not None and fast.next.next is not None:while fast is not None and fast.next is not None:
A list that never ends
What if following next never reaches None? A cycle is a loop in the links: some node's next points back to an earlier node, or to itself, so a walk goes around the same nodes forever. A function that walks until None never returns on such a list. How can a walk notice it is going in circles?
The first answer is a notebook of the nodes already passed. Walk the list and put each node in a set. The set holds the node objects themselves, not their values, so two nodes that both hold 4 are two entries. Meeting a node that is already in the set means a cycle; reaching None means there is none. That costs O(n) time and O(n) extra space, because the set can end up holding every node.
Two speeds catch a cycle with no set at all. Picture two runners on a circular track: the faster one comes around and catches the slower one. Both walkers start at the head, with the loop condition of the middle walk. Without a cycle, fast reaches the end and the loop stops. With one, there is no end: sooner or later both walkers are going around the loop. This is Floyd's cycle check, also called the tortoise and the hare.
Why must they meet? Count the gap: how many one-node moves take fast forward to slow. Once both are in the loop, each step slow moves one node away and fast closes in by two, so the gap shrinks by exactly one node per step. A gap that drops by one at a time cannot skip over 0, so the two land on the same node.
The trace builds 7 → 3 → 9 → 4 → 6, then points the 6 back at the 3, so the loop is 3, 9, 4, 6. Before you step through, guess on which node the walkers meet.
def has_cycle(head):slow = headfast = headwhile fast is not None and fast.next is not None:slow = slow.nextfast = fast.next.nextif slow is fast:return Truereturn Falsehead = build_list([7, 3, 9, 4, 6])last = head.next.next.next.nextlast.next = head.nextprint(has_cycle(head))
(nothing printed yet)Compare nodes with is, never values with ==. slow is fast asks whether both names refer to the same node object. Two different nodes can hold equal values, and that is not a cycle.
Type exactly what this prints.
head = build_list([4, 4, 4])
slow = head.next
fast = head.next.next
print(slow.val == fast.val)
print(slow is fast)
Now write it. The tests build lists with and without a cycle, including one node that points to itself.
The solution is the function you traced. The loop condition already handles the small cases: an empty list (fast is None at once) and one node with no cycle (fast.next is None at once) both return False without entering the loop. A node that points to itself is caught after one step, when both walkers land back on it.
How many passes until they meet? Work one by hand. This time the whole list is the loop.
In 2 → 4 → 6 → 8 → 10, the last node points back to the head, so the whole list is one loop of five nodes. Both walkers start on the 2. Each pass of the loop moves slow one node and fast two, then checks slow is fast.
On paper, write one row per pass: where slow is, where fast is, and the gap (how many one-node moves take fast forward to slow). After how many passes is slow is fast true?
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
When the walkers meet, both are inside the loop. That makes measuring the loop one more short walk: go around it once from the meeting node.
Write cycle_length(head). If the list has a cycle, return how many nodes are in the loop; if it ends in None, return 0. In 7 → 3 → 9 → 4 → 6 with the 6 pointing back to the 3, the loop is 3, 9, 4, 6, so the answer is 4. Use O(1) extra space: no set. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.A fixed gap: the n-th node from the end
Node number n from the end counts backwards: the last node is number 1, the one before it number 2, and so on. In 11 → 22 → 33 → 44 → 55 → 66, number 2 from the end is 55. The list only walks forward, so how do we find it in one walk? (In this section n is that count, so we write L for the number of nodes.)
The two-pass answer counts first. Walk once to learn L, then walk L − n steps from the head. That is correct and O(L). The one-walk answer keeps two walkers at the same speed, with a gap. Move fast n nodes ahead of slow. Then move both one node per step. The gap never changes, so when fast walks off the end onto None, slow is n nodes behind it: number n from the end. Think of a ruler n nodes long, slid along the list until its front end falls off.
The trace runs it on those six nodes with n = 2. for _ in range(n) repeats its body n times; _ is the usual name for a loop variable whose value nobody reads, and in the trace it only counts 0, 1. Before you step through, guess how many times the while loop's body runs.
def nth_from_end(head, n):fast = headslow = headfor _ in range(n):fast = fast.nextwhile fast is not None:fast = fast.nextslow = slow.nextreturn slow
(nothing printed yet)Run the gap trace in your head with n = 4 instead of 2, on the same six nodes 11 → 22 → 33 → 44 → 55 → 66. How many times does the body of the while loop run? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
To remove a node, you need the node before it. Removing changes one link: the node before the target skips over it, before.next = before.next.next. So stop one node earlier: move both only while fast.next is not None, which leaves fast on the last node. Then slow is n nodes behind number 1, which makes it number n + 1 from the end: the node right before the one to remove.
One case has no node before it: removing the head, when n equals L. Started on head, the walk even crashes there: n moves put fast on None, and the test reads .next from None. The fix is the dummy head from the previous lesson: a placeholder node in front of the real head. Here it is made with dummy = ListNode(0, head), so its next is the head from the start. Start both walkers on dummy instead of head. When n equals L, slow never leaves dummy, which is exactly the node before the head. At the end, return dummy.next: the old head, or the new one if the old one was removed.
Here is the removal walk on the same six nodes with n = 2. Both walkers start on dummy, the placeholder in front of the 11. The table shows where each one stands:
| After | fast on | slow on |
|---|---|---|
the for loop | 22 | dummy |
| pass 1 | 33 | 11 |
| pass 2 | 44 | 22 |
| pass 3 | 55 | 33 |
| pass 4 | 66 | 44 |
fast is on the last node, so the walk stops with slow on the 44, right before the 55. slow.next = slow.next.next links the 44 to the 66, and the list from dummy.next reads 11 → 22 → 33 → 44 → 66. It takes the same 4 passes as the trace, with both walkers one node further back. With n = 6, the target is the head. The for loop carries fast from dummy onto the 66, the while loop never runs, and slow stays on dummy. Then dummy.next skips the 11, and the new head is the 22.
Now the full problem. The tests remove the head, the last node, and the only node of a one-node list.
Every edge case runs through the same lines, which is the point of the dummy. With n = 1 on two or more nodes, slow stops on the second-to-last node. When n equals L, slow stays on dummy. Removing the only node sets dummy.next to None, the empty list. The walkers count positions and never compare values, so repeated values cannot confuse them.
One tool, three walks
All three walks use the same two names, slow and fast, with a different rule for moving them. As in the last section, L is the number of nodes and n counts from the end.
| Problem | How they move | The walk stops when | Then slow is |
|---|---|---|---|
| Middle | 1 and 2 nodes per step | fast cannot move two more nodes | the middle node, at position L // 2 |
| Cycle | 1 and 2 nodes per step | fast reaches the end (no cycle), or slow is fast | the meeting node, inside the loop (when there is a cycle) |
| Remove number n from the end | both start on dummy; fast goes n ahead, then both 1 per step | fast is on the last node | the node right before the target |
All three take one walk, with time in step with the length of the list, and O(1) extra space. What the pointers buy differs. For the cycle, they replace a set that can hold every node, so O(n) extra space drops to O(1). For the middle and the n-th from the end, counting first already uses O(1) space; the pointers turn two walks into one. Two more problems in this module's practice bank start from the middle walk: Reorder List (LeetCode 143) and Palindrome Linked List (LeetCode 234).
Last, practice saying the gap version the way you would in the room.
An interviewer asks you to remove the n-th node from the end of a singly linked list, then adds: "Can you do it in one pass?" In a few plain sentences, say the plain answer first, then the one-pass plan with its walk, notebook, promise and cost, and the edge case the dummy head handles.
Saved in this browser as you type.