Find a loop and where it starts, where two lists meet, and a node k from the end, with two pointers at different speeds.
You work on the platform behind a chat app. Your team lead brings four questions about chains:
A walk that waits for null answers the first question badly. If the chain loops, the walk never ends, and you never learn why. The answer is to send two walkers down the chain at different speeds.
Picture two runners who start together. One runs at a steady pace, and the other runs twice as fast. On a straight road the fast runner reaches the finish first, and they never meet again.
On a circular track the fast runner keeps lapping, and sooner or later comes up behind the slow one. Meeting means the track is a circle, and no finish line exists. In a chain, the runners are two cursors, the road is the chain, and a circle is a loop.
Two runners: on a straight road the fast one finishes alone, and on a circular track the fast one laps the slow one.
A loop is not a new kind of node. It is one node whose next pointer holds the address of an earlier node. Each node still has exactly one next, so a walk from the head either reaches null or repeats.
The picture below is a plain chain. A loop appears when the last node stores an earlier address.
Step by step: A chain in memory: a loop would be one stored address. The animated player loads in your browser.
Most problems in this lesson give the chain as a table of next slots instead of nodes. Slot i is a node, and after[i] is its next pointer: the slot it leads to, or -1 for null. A walk starts at a given slot.
after = [1, 2, 3, 4, 2], start = 0
slot: 0 1 2 3 4
after: 1 2 3 4 2 the walk: 0 → 1 → 2 → 3 → 4 → 2 → 3 → ...That is the loop in the picture: slot 4 leads back to slot 2. Every move on nodes has a table version. curr = curr.next becomes curr = after[curr], and curr is None becomes curr == -1.
Why a table? A test written as a list of values, such as [0, 1, 2, 3, 4], can only describe a chain that ends. It cannot say "and the last node points back at node 2", or "these two chains share their last nodes". A table can, so the tests for loops and joins use one.
Slots that the walk never reaches can hold any value, and they do not change the answer.
Four words come up below:
Predict what happens
Q A chain has 5 nodes in a straight line, with no loop. slow and fast start at the head. What happens to fast?
Answer: B
Without a loop there is no way back. Fast moves two nodes a round, reaches the end first and falls off it, so the walk stops with no meeting.
Start slow and fast on the same node. Each round, slow takes one step and fast takes two. If fast reaches null, or has no node two ahead, the chain ends. If slow and fast stand on the same node after a move, the chain has a loop.
Take nodes 0 to 4, where node 4 points back at node 2. The tail is nodes 0 and 1, so it has 2 nodes. The loop is nodes 2, 3 and 4, so it has 3 nodes.
| Round | slow | fast |
|---|---|---|
| start | 0 | 0 |
| 1 | 1 | 2 |
| 2 | 2 | 4 |
| 3 | 3 | 3 |
In round 3, fast goes 4, then 2, then 3. Both stand on node 3, so there is a loop.
Why do they always meet? Wait until slow enters the loop, where fast already is, and count the steps fast would need, going forward round the loop, to reach slow. Each round slow moves one step away and fast moves two steps closer, so that distance shrinks by exactly one. It cannot jump from 1 past 0, so within one lap of slow, fast lands on slow.
The exact round follows from counting. After t rounds slow has taken t steps and fast 2t, so fast is t steps ahead. They share a node only when both are in the loop, so t is at least the tail length. And the lead t must be a whole number of laps.
So they meet at the first round that is a multiple of the loop length and at least the tail length. Here that is 3, which is a multiple of 3 and at least 2. That round is never more than the tail plus the loop, which is at most the number of nodes, so detection is O(n).
To measure the loop, keep one cursor on the meeting node and walk the other round, counting steps until it comes back. Here it takes 3 steps: 3, 4, 2, and back to 3.
Detect a loop: slow takes one step and fast takes two from the same node, and if they ever stand on the same node, the chain loops.
Exercise · Predict the output: When do slow and fast meet?. A chain is stored as a table of next slots. The code moves slow one slot and fast two slots a round, and stops when they stand on the same slot. What does it print: the number of rounds, then the slot where they meet?
after = [1, 2, 3, 4, 5, 6, 3]
slow = 0
fast = 0
rounds = 0
while True:
slow = after[slow]
fast = after[after[fast]]
rounds += 1
if slow == fast:
break
print(rounds, slow)The same two speeds find the middle. When fast runs off the end, slow has covered half the chain.
Step by step: The middle of seven nodes. The animated player loads in your browser.
With eight nodes, slow stops on the second of the two middles.
Step by step: The middle of eight nodes. The animated player loads in your browser.
Predict what happens
Q A loop has a tail of 4 nodes and a loop length of 3. At which round do slow and fast first stand on the same node?
Answer: C
Both must be inside the loop, so the round is at least 4. Fast is that many nodes ahead of slow, and they share a node when the lead is a whole number of laps. The first multiple of 3 that is at least 4 is 6.
Exercise · Put it in order: The loop check. Arrange the lines into a check that says whether a walk through a table of next slots ever loops. Slot -1 means null.
def has_loop(after, start):
slow = start
fast = start
while fast != -1 and after[fast] != -1:
slow = after[slow]
fast = after[after[fast]]
if slow == fast:
return True
return False
fast = after[fast]The meeting node can be anywhere in the loop. To find where the loop begins, leave slow where it is and start a new walker at the head. Move both one node at a time. They meet on the first node of the loop.
In the example, they met on node 3. The walker starts on node 0, and slow starts on 3. After one step the walker is on 1 and slow on 4. After two steps both are on node 2, where the loop begins.
Why does it work? Call the tail length T and the loop length L. Count everything in steps from the head.
In the example, T = 2, L = 3 and t = 3. Slow has taken 3 steps, and 2 more make 5 = 2 + 3, so it stands on node 2, the start of the loop. If the tail is longer than the loop, slow goes round more than once during those T steps, and the argument does not change.
Find where the loop begins: leave slow at the meeting node, start a new walker at the head, and step both until they meet.
Predict what happens
Q In the example, slow and fast meet on node 3. The loop begins on node 2. A new walker starts on node 0 and slow stays on 3. Where do they meet?
Answer: C
The tail has 2 nodes, so the walker needs 2 steps to reach node 2. From node 3, slow goes to 4 and then to 2 in the same 2 steps.
Two chains can join and share every node from some point. They have different lengths before the join, so two walkers that start together reach it at different times. Let each walker, after the end of its own chain, continue on the other chain. Count the end of a chain as one step.
Say chain A has a own nodes, chain B has b own nodes, and they share c nodes. Walker A covers a + c nodes, one step onto null, then b nodes of chain B: a + c + 1 + b steps, and it stands on the first shared node. Walker B covers b + c + 1 + a, the same number. If a = b, they meet there even sooner, on the first pass.
If there is no shared node, c = 0. Then both walkers stand on null after a + b + 1 steps, or after a steps when a = b. Null equals null, so the loop while A != B stops, and the answer is null.
That is why the step onto null matters. A version that jumps straight from the last node to the other chain never stands on null, so on two separate chains it runs for ever.
A second way gives the same answer. Count both lengths, move the walker on the longer chain forward by the difference, then move both together until they are equal. It is also O(1) memory, with two extra walks to count.
Find where two chains join: each walker continues on the other chain, so both cover the same distance and arrive together.
A chain does not know its length, but a gap does. Put fast k - 1 nodes ahead of slow, then move both one node at a time. When fast is on the last node, slow is k - 1 nodes behind it, on the k-th node from the end. The last node is number 1.
Take 1, 2, 3, 4, 5 and k = 2. Fast starts on node 2, one node ahead. After three moves fast is on 5, and slow is on 4, the second node from the end.
To delete that node you need the one before it. Start both cursors on a placeholder node before the head, and put fast k nodes ahead. When fast is on the last node, slow is on the node right before the k-th from the end, so its next is the k-th. The placeholder matters when the k-th from the end is the head itself: slow then stays on the placeholder, and the delete still works.
A rotation by k uses the same gap. To move the last k nodes to the front, you cut after the node right before them. So put fast k nodes ahead of slow, both from the head, and stop when fast is on the last node. First reduce k to k mod n: rotating by the whole length changes nothing, and a longer gap would run fast off the end.
Find the k-th node from the end: put fast k minus one nodes ahead, move both until fast is on the last node.
Exercise · Find the bug: The wrong node leaves. This function deletes the k-th node from the end of a list (the last node is number 1), with a gap of k between two cursors. It deletes a node next to the right one. Which line is wrong?
def remove_kth_from_end(head, k):
dummy = ListNode(0, head)
slow = head
fast = dummy
for _ in range(k):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return dummy.nextPredict what happens
Q A chain has 7 nodes: 10, 20, 30, 40, 50, 60, 70. Fast starts 3 nodes ahead of slow, both from the head, and they move until fast is on the last node. Where is slow?
Answer: B
Fast starts on node 40, three ahead of the head, and ends on 70. Slow moves the same distance, from 10 to 40. That is the node right before the last 3, the 4th from the end.
Exercise · Break it: Find the input this rotation cannot take. This function moves the last k nodes of a list to the front, with a gap of k between two cursors. Find an input where it gives the wrong answer or crashes.
def rotate_right(head, k):
if head is None or k == 0:
return head
slow = head
fast = head
for _ in range(k):
fast = fast.next
while fast.next:
slow = slow.next
fast = fast.next
new_head = slow.next
slow.next = None
fast.next = head
return new_headEach move is one or two walks and a few cursors. The gap and the two speeds replace counting and remembering.
| Operation | Two cursors | The plain alternative |
|---|---|---|
| Detect a loop | O(n) time, O(1) memory | A set of visited nodes: O(n) time, O(n) memory |
| Find where a loop begins, walking from the head | O(n) time, O(1) memory: two phases | A set of visited nodes: the first repeat, O(n) memory |
| Find the middle node | O(n) time, one walk, O(1) memory | Count the nodes, then walk half: two walks |
| Reach the k-th node from the end | O(n) time, one walk | Count first, then walk n - k: two walks |
| Find the first shared node of two joined chains | O(n) time, O(1) memory | Write one chain into a set, then scan the other: O(n) memory |
| Link the tail to the node at an index | O(i): i hops from the head | The same: an index is still a walk |
The two cursors never beat the plain alternatives on time. They win on memory, and on needing one walk instead of two.
Drive the chain yourself and read the hop counter. The sandbox shows the middle, which is the first use of two speeds. Loops, joins and gaps are drawn in the lecture and the clips.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build a chain that can be closed into a loop, and detect it. The lab gives you a Node class and a LoopyList class that keeps head, tail and a count. You write push_back, link_tail_to, has_loop, loop_length, unlink_loop and size.
The seventh, to_list, is written for you. It stops after count nodes, so it is safe on a loop.
has_loop and loop_length need the two cursors.
unlink_loop needs both phases. Find the first node of the loop, walk round to the node that points back at it, and set its next to null.
Three rules keep the list correct:
link_tail_to(position) points the tail's next at the node at that position, once. It does nothing on an empty list, when a loop exists already, or when the position is out of range.push_back does nothing while the list has a loop, because a loop has no end to add to.count goes up by one on each push, and never changes otherwise.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use two cursors when you must answer a question about a chain in one pass with no extra memory. Examples are: does it loop, where is the middle, which node is k from the end. They also help when values are positions, as in a table of next slots.
In an interview, naming the gap or the two speeds before you code shows that you see the structure of the problem.
If memory is not a concern, a set of visited nodes is simpler to write and to explain. It also finds the first repeated node directly.
Do not use fixed speeds on a chain that another part of the program is changing while you walk. The nodes can move under you, and the meeting can be missed or invented. Copy first, or lock the chain.
Slow and fast start on the same node. If the loop checks slow == fast before the first move, it is true at once. On 1 → 2 → 3 with no loop, the code answers that there is a loop. Move first, then compare.
The classic off by one in a gap: looping while fast is not null moves both cursors one node too far, so slow ends one node late.
Fast moves two nodes, so the loop must test both fast and fast.next before it reads fast.next.next. If it tests only fast.next, an empty chain crashes. If it tests only fast, a chain of one node crashes on fast.next.next. Test fast != null && fast.next != null.
To rotate a chain by k, the loop must stop when fast.next is null, so fast is on the last node. If it stops when fast is null, both cursors go one node too far. On 1 → 2 → 3 → 4 → 5 with a gap of 2, slow ends on 4 instead of 3, and the rotation returns 5, 1, 2, 3, 4 instead of 4, 5, 1, 2, 3.
Slow and fast can meet anywhere in the loop. With the loop 2, 3, 4 they meet on node 3, so return slow answers 3, but the loop begins on node 2. Return the node where the new walker and slow meet.
fast and fast.next before moving, move before you compare, and test the empty chain, one node and two nodes.Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · Why it works
Q1/3 Why do slow and fast need no record of the nodes they have visited?
Answer: B
The two outcomes are different without any record. A chain that ends lets fast fall off the end, and a loop makes fast lap slow.
Q2/3 Inside a loop, why can fast not jump over slow?
Answer: C
The gap closes one node at a time. A gap that changes by one cannot go from positive to negative without being zero.
Q3/3 A chain has a tail of 5 nodes and a loop of 4 nodes. At which round do slow and fast first stand on the same node?
Answer: C
Both must be in the loop, so the round is at least 5, and the lead of fast must be a whole number of laps. The first multiple of 4 that is at least 5 is 8.
Checkpoint · Where the loop begins
Q1/4 Slow and fast first meet on node 6 of a chain whose loop begins on node 4. What is the answer to "where does the loop begin"?
Answer: B
The meeting node can be anywhere in the loop. A second phase finds the first node of the loop.
Q2/4 In the second phase, which two cursors take one step at a time?
Answer: B
Both take one step a round. Slow has taken a whole number of laps' worth of steps, so a tail's length more puts it on the first node of the loop, and the new walker from the head needs exactly a tail's length to get there.
Q3/4 Two chains join and share their last nodes. Why does each walker continue on the other chain after its own ends?
Answer: B
The own parts can have different lengths. Swapping makes the totals equal, so the walkers stand on the first shared node on the same step.
Q4/4 Two chains share no node. Where do the two walkers meet?
Answer: B
Each walker covers both chains and then the end, the same number of steps. Counting the end as a step makes them equal there.
Checkpoint · The gap
Q1/3 A chain is 1, 2, 3, 4, 5, 6, 7, 8. Fast starts 2 nodes ahead of slow, both from the head, and both move until fast is on the last node. Where is slow?
Answer: C
Fast starts on 3 and ends on 8, so it moves 5 nodes. Slow moves 5 nodes too, from 1 to 6. A gap of k - 1 = 2 reaches the k = 3rd node from the end.
Q2/3 To delete the 2nd node from the end of 1, 2, 3, 4, 5, you start both cursors on a placeholder before the head and put fast 2 nodes ahead. When fast is on the last node, where is slow?
Answer: C
Fast starts on 2 and ends on 5, so it moves 3 nodes. Slow moves from the placeholder to 3. Slow.next is 4, the node to delete.
Q3/3 Which loop condition is safe when fast moves two nodes at a time?
Answer: C
The loop reads fast.next.next, so both fast and fast.next must exist. Testing only one crashes on the empty chain or on an odd length.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.