iq.lab
Python starts when a code cell comes near or you run one
07 Linked lists

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.

About 1 hour 35 minutes, with the 3 problems worked in it
By the end you can
  • Trace slow and fast through a linked list and say where each one stops on odd and even lengths

  • Write a loop condition that never reads .next from None

  • Detect 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.

Step throughTwo speeds on one list
Step 1 of 12
Line 1 is about to run.
build_list links five nodes and returns the first one.
head = build_list([8, 3, 5, 2, 7])
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)
Names
no names yet
Output
(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.

PredictThe middle of an even list

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.

Quick checkWhich condition is safe?

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.

easyLinked listsTwo pointers target 15 min

Middle of a linked list

You get head, the first node of a linked list with at least one node. Each node is a ListNode with a value (node.val) and a link (node.next) to the node after it.

Return the middle node itself, a node of the given list, not a copy. Counting positions from 0, a list of n nodes has its middle at position n // 2. When n is even, two nodes share the middle, and position n // 2 is the later of the two.

Examples write a linked list as the list of its values: [4, 9, 1] means 4 → 9 → 1. An output is the list that starts at the node you return.

Example 1
Inputhead = [4, 9, 1, 6, 3]Output[1, 6, 3]

Five nodes, so the middle is at position 5 // 2 = 2: the node holding 1. From it the list reads 1, 6, 3.

Example 2
Inputhead = [2, 8, 5, 7]Output[5, 7]

Four nodes have two middles, 8 and 5. Position 4 // 2 = 2 is the second one, 5.

Constraints
  • 1 ≤ number of nodes ≤ 100

  • 1 ≤ node value ≤ 100

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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 in orderThe first middle

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • def first_middle(head):
    • return slow
    • slow, fast = slow.next, fast.next
    • slow, fast = head, head
    • slow, fast = slow.next, fast.next.next
    • while 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.

    Step throughTwo speeds around a loop
    Step 1 of 26
    Line 1 is about to run.
    def has_cycle(head):
    slow = head
    fast = head
    while fast is not None and fast.next is not None:
    slow = slow.next
    fast = fast.next.next
    if slow is fast:
    return True
    return False
    head = build_list([7, 3, 9, 4, 6])
    last = head.next.next.next.next
    last.next = head.next
    print(has_cycle(head))
    Names
    no names yet
    Output
    (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.

    PredictEqual is not the same

    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.

    easyLinked listsTwo pointers target 15 min

    Linked list cycle

    You get head, the first node of a linked list, or None if the list is empty. Each node is a ListNode with a value (node.val) and a link (node.next) to the node after it.

    In a healthy list, following next from the head ends at None. In a broken one, the last node's next points back to an earlier node, or to itself, so following next goes around the same nodes forever. That loop is a cycle. Return True if the list has a cycle and False if it does not.

    Examples describe a list by its values and pos, the position (counting from 0) of the node that the last node points back to. pos = -1 means there is no cycle. Your function receives only head.

    Example 1
    Inputvalues = [5, 1, 8, 2], pos = 1OutputTrue

    The 2 points back to the 1, so the walk goes 5, 1, 8, 2, 1, 8, 2, and so on forever.

    Example 2
    Inputvalues = [4, 7], pos = 0OutputTrue

    The 7 points back to the 4.

    Example 3
    Inputvalues = [6, 3, 9], pos = -1OutputFalse

    The 9's next is None, so the walk ends.

    Constraints
    • 0 ≤ number of nodes ≤ 104

    • -105 ≤ node value ≤ 105

    • pos is -1 or a valid position in the list.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    On paperWhere they meet

    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.

    Passes until slow is fast

    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.

    Code itHow long is the loop?

    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.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says 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.

    Step throughTwo walkers with a gap of n
    Step 1 of 24
    Line 1 is about to run.
    def nth_from_end(head, n):
    fast = head
    slow = head
    for _ in range(n):
    fast = fast.next
    while fast is not None:
    fast = fast.next
    slow = slow.next
    return slow
    Names
    no names yet
    Output
    (nothing printed yet)
    Work it outA wider gap

    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.

    passes

    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:

    Afterfast onslow on
    the for loop22dummy
    pass 13311
    pass 24422
    pass 35533
    pass 46644

    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.

    mediumLinked listsTwo pointers target 25 min

    Remove the n-th node from the end

    You get head, the first node of a linked list, and an integer n. Each node is a ListNode with a value (node.val) and a link (node.next) to the node after it, or None after the last node.

    Number the nodes from the end: the last node is number 1, the one before it is number 2, and so on. Remove node number n and return the first node of the shortened list.

    The node to remove can be the head itself. Then the second node becomes the new head, and a one-node list becomes empty, so you return None.

    Remove the node by changing links: the nodes that stay must be the original node objects, not copies. Examples write a linked list as the list of its values: [6, 7, 8] means 6 → 7 → 8, and [] is an empty list.

    Example 1
    Inputhead = [10, 20, 30, 40, 50], n = 2Output[10, 20, 30, 50]

    Counting from the end, 50 is number 1 and 40 is number 2. So 40 goes.

    Example 2
    Inputhead = [6, 7, 8], n = 3Output[7, 8]

    Number 3 from the end is the head, so 7 becomes the new head.

    Example 3
    Inputhead = [9], n = 1Output[]

    Removing the only node leaves an empty list, so the function returns None.

    Constraints
    • 1 ≤ number of nodes ≤ 105

    • 1 ≤ n ≤ number of nodes

    • Node values are integers and may repeat.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    ProblemHow they moveThe walk stops whenThen slow is
    Middle1 and 2 nodes per stepfast cannot move two more nodesthe middle node, at position L // 2
    Cycle1 and 2 nodes per stepfast reaches the end (no cycle), or slow is fastthe meeting node, inside the loop (when there is a cycle)
    Remove number n from the endboth start on dummy; fast goes n ahead, then both 1 per stepfast is on the last nodethe 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.

    Say itSay it like 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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Designing an LRU cache