Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 1

Two Speeds Through One List

Use slow and fast pointers for single-pass middle finding, Floyd cycle detection and entry recovery, k-th node from the end with a k-step lead, and two-list intersection.

Contentsand lesson path

What you will learn

  • Use fast and slow pointers to find the middle node and detect a cycle, and explain why the pointers must meet.

Prerequisites: Complexity Analysis

01. The problem

Suppose you receive only the head reference of a singly linked list and must answer structural questions in one traversal and O(1) extra space—no copying nodes into a Python list and no storing visited id(node) entries in a set: find the middle node, detect whether a buggy .next link forms a cycle (and locate where the cycle enters), locate the k-th node from the end, or check whether two lists merge into a shared suffix.

A two-pass count-then-walk approach fails immediately if a cycle exists (the first counting pass loops forever), while a seen: set[int] consumes O(n) extra memory. In this worked example we build and verify four two-pointer mechanics: 1x/2x middle finding, Floyd's cycle detection with its gap-shrinking proof, a fixed k-step lead, and length-equalizing head switching for intersection.

02. Step 1: finding the middle in one pass without counting length

Start both pointers at head: slow = fast = head. On each step k (while fast is not None and fast.next is not None:), slow advances 1 link (to 1-based position k + 1) while fast advances 2 links (to position 2k + 1). When fast lands on the last node or steps past it to None, slow sits halfway across the chain.

Compare an odd list 10 -> 20 -> 30 -> 40 -> 50 with an even list 10 -> 20 -> 30 -> 40 -> 50 -> 60. On the odd list, fast hops 10 -> 30 -> 50 (stopping because 50.next is None), leaving slow on the unique middle 30. On the even list, fast hops 10 -> 30 -> 50 -> None in three steps, leaving slow at 40 (the second middle node). By contrast, middle_first starts fast = head.next (at 20), hops 20 -> 40 -> 60, and stops because 60.next is None, leaving slow at 30 (the first middle node, which you used in split_middle).

Python · middle_second vs middle_first on odd and even lists
from dataclasses import dataclass


@dataclass(eq=False)
class Node:
    val: int
    next: "Node | None" = None


def from_list(vals: list[int]) -> Node | None:
    dummy = tail = Node(0)
    for v in vals:
        tail.next = Node(v)
        tail = tail.next
    return dummy.next


def middle_second(head: Node | None) -> Node | None:
    slow = fast = head
    while fast is not None and fast.next is not None:
        assert slow is not None
        slow = slow.next
        fast = fast.next.next
    return slow


def middle_first(head: Node | None) -> Node | None:
    if head is None:
        return None
    slow = head
    fast: Node | None = head.next
    while fast is not None and fast.next is not None:
        assert slow.next is not None
        slow = slow.next
        fast = fast.next.next
    return slow


odd = from_list([10, 20, 30, 40, 50])
even = from_list([10, 20, 30, 40, 50, 60])
m_odd = middle_second(odd)
m_even2 = middle_second(even)
m_even1 = middle_first(even)
print("odd middle:", m_odd.val if m_odd else None)
print("even second:", m_even2.val if m_even2 else None)
print("even first:", m_even1.val if m_even1 else None)
Expected output
odd middle: 30
even second: 40
even first: 30

03. Step 2: Floyd cycle detection—why fast must catch slow

If a list contains a cycle of length L >= 1, fast never hits None. Once both pointers are inside the loop, why can fast never leap past slow forever—even when L is odd?

Measure the forward distance d along the cycle from fast ahead to slow (0 <= d < L). Each iteration advances slow by 1 (increasing d by 1) and advances fast by 2 (decreasing d by 2). The net change is 1 - 2 = -1 modulo L! Because d shrinks by exactly 1 node per step (d, d - 1, ..., 2, 1, 0), d cannot skip from 1 to -1 and must reach 0 within at most L iterations inside the cycle.

To locate the cycle entry node, suppose the tail before the entry has a edges and the meeting point sits b edges past the entry (0 <= b < L). When they first meet, slow has walked a + b steps and fast has walked 2(a + b) steps, which equals a + b + k * L for some positive integer k (fast lapped slow k times). Subtracting a + b gives a + b = k * L, so a = k * L - b. Therefore, resetting a fresh pointer p at head while keeping slow at the meeting point and advancing both at speed 1 moves p a steps to the entry node while slow walks a = k * L - b steps from b—completing k * L steps past the entry and landing on the exact same entry node!

Trace that on 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 30 (a = 2, L = 4): slow steps 10 -> 20 -> 30 -> 40 -> 50 while fast jumps 10 -> 30 -> 50 -> 30 -> 50, meeting at 50 (b = 2). Phase 2 walks p (10 -> 20 -> 30) and slow (50 -> 60 -> 30) two steps each to converge at entry 30.

When NOT to use Floyd's algorithm: in debugging scripts over small in-memory graphs where O(n) space is fine, a seen: set[int] storing id(node) stops on the very first revisit to the entry node with simpler code and zero phase-2 math.

Text · gap from fast to slow shrinks by 1 per step inside cycle L = 4
10 ---> 20 ---> [30] ---> [40] ---> [50] ---> [60]
                 ^                             |
                 |_____________________________|  (cycle L = 4)
Inside cycle: slow += 1, fast += 2  =>  forward gap (fast -> slow) drops by 1
Python · has_cycle and cycle_start with object identity (is)
from dataclasses import dataclass


@dataclass(eq=False)
class Node:
    val: int
    next: "Node | None" = None


def has_cycle(head: Node | None) -> bool:
    slow = fast = head
    while fast is not None and fast.next is not None:
        assert slow is not None
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False


def cycle_start(head: Node | None) -> Node | None:
    slow = fast = head
    while fast is not None and fast.next is not None:
        assert slow is not None
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            p = head
            while p is not slow:
                assert p is not None and slow is not None
                p = p.next
                slow = slow.next
            return p
    return None


nodes = [Node(v) for v in (10, 20, 30, 40, 50, 60)]
for i in range(5):
    nodes[i].next = nodes[i + 1]
print("acyclic has_cycle:", has_cycle(nodes[0]))
nodes[5].next = nodes[2]
entry = cycle_start(nodes[0])
print("cyclic has_cycle:", has_cycle(nodes[0]))
print("cycle entry:", entry.val if entry else None)
solo = Node(7)
solo.next = solo
solo_entry = cycle_start(solo)
print("self-loop:", has_cycle(solo), "| entry:", solo_entry.val if solo_entry else None)
Expected output
acyclic has_cycle: False
cyclic has_cycle: True
cycle entry: 30
self-loop: True | entry: 7

04. Step 3: k-th node from the end and two-list intersection

Two related single-pass, O(1)-space pointer tricks complete your linked-list toolkit:

  • k-th node from the end with a k-step lead: move lead forward k times while follow stays at head (if lead hits None before k steps, the list has fewer than k nodes so return None). Now advance both lead and follow at 1x together until lead is None: since lead always stays k steps ahead, follow lands exactly k nodes before None (so k = 1 returns the tail node).
  • Intersection point of two acyclic lists (head_a, head_b): suppose list A has len_a nodes before None and list B has len_b nodes before None, sharing a common suffix of c nodes (0 if disjoint). Start pa = head_a and pb = head_b, and advance pa = pa.next if pa is not None else head_b (and symmetrically pb = pb.next if pb is not None else head_a). Each pointer walks its own list, steps onto None, and switches to the other list's head—traversing len_a + 1 + len_b transitions in total! If the lists intersect, pa is pb matches at the exact shared entry node; if they are disjoint, both pa and pb reach None simultaneously—after len_a steps if the lengths are equal, or otherwise after len_a + len_b + 1 steps—ending the loop cleanly with None.

Predict before running: in the snippet below, ha has length 4 (10 -> 20 -> 40 -> 50) and hb has length 3 (99 -> 40 -> 50), sharing node 40. Why must the comparison use pa is not pb rather than pa.val != pb.val?

Python · kth_from_end and intersection_node in O(1) space
from dataclasses import dataclass


@dataclass(eq=False)
class Node:
    val: int
    next: "Node | None" = None


def from_list(vals: list[int]) -> Node | None:
    dummy = tail = Node(0)
    for v in vals:
        tail.next = Node(v)
        tail = tail.next
    return dummy.next


def kth_from_end(head: Node | None, k: int) -> Node | None:
    if k <= 0:
        return None
    lead = follow = head
    for _ in range(k):
        if lead is None:
            return None
        lead = lead.next
    while lead is not None:
        assert follow is not None
        lead = lead.next
        follow = follow.next
    return follow


def intersection_node(head_a: Node | None, head_b: Node | None) -> Node | None:
    pa, pb = head_a, head_b
    while pa is not pb:
        pa = pa.next if pa is not None else head_b
        pb = pb.next if pb is not None else head_a
    return pa


seq = from_list([10, 20, 30, 40, 50])
k2 = kth_from_end(seq, 2)
print("2nd from end:", k2.val if k2 else None, "| k=8:", kth_from_end(seq, 8))
shared = Node(40, Node(50))
ha = Node(10, Node(20, shared))
hb = Node(99, shared)
hit = intersection_node(ha, hb)
print("shared node val:", hit.val if hit else None)
print("disjoint:", intersection_node(from_list([1, 2, 3]), from_list([4, 5])))
Expected output
2nd from end: 40 | k=8: None
shared node val: 40
disjoint: None

05. Check your understanding

Practice check · 3 questions

Two-pointer mechanics

Verify cycle invariants, self-loops and intersection termination.

Q1. Inside a cycle of length `L = 4`, what happens if `fast` advances 3 nodes per step while `slow` advances 1 node per step?
Q2. A 1-node list `n = Node(7)` points to itself (`n.next = n`). What do `has_cycle(n)` and `cycle_start(n)` return?
Q3. Two disjoint acyclic lists have lengths `3` and `5`. In the head-switching loop (`pa = pa.next if pa is not None else head_b`), when does `while pa is not pb:` end?
Practice only: not graded, not saved, not evidence.

06. Apply it

Write a pytest suite verifying middle_second, has_cycle, cycle_start, kth_from_end, and intersection_node on: empty list None, 1-node acyclic list, 1-node self-loop, odd/even acyclic lists, k = 1 and k > len, intersecting lists with equal vs unequal prefix lengths, and disjoint lists.

Next, measure when linked lists lose to built-in Python structures and when dict + DLL genuinely wins in Lists, Arrays or Deques?.

07. Review prompt

Without looking back:

  1. Why does slow = fast = head stop at the second middle on even lengths while fast = head.next stops at the first middle?
  2. Prove in two sentences why 2x vs 1x cannot skip over slow inside a cycle of any length L >= 1.
  3. Why does the head-switching intersection loop terminate even when two lists share no nodes at all?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check