Skip to contentKEEP THE CRAFTTHE SANCTUARY

Fast and Slow Pointers

Follow one deterministic successor with two speeds to distinguish termination from a cycle, then recover the entry in a separate phase. Index-linked Labs make the null sentinel and each successor step visible.

1 practice exercise6 interview problems

Recognize it when Each state has exactly one next state or an explicit termination sentinel.

Checking your account…

Fast and Slow Pointers Code Labs

Model One Successor Before Adding a Runner

Use a list of next indices to represent a chain: each entry names exactly one successor, and -1 means termination. This representation is different from a graph with several neighbors. A seen set can detect a revisit directly; fast and slow runners trade that stored history for a relationship between their positions.

Advance Before Testing for a Meeting

Both runners start at head, so their initial equality says nothing about a cycle. Each iteration moves slow once and fast twice. If fast or its first successor is -1, the second step must not be attempted. Once both runners are inside a cycle, fast gains one position relative to slow per iteration and eventually closes the modular gap.

Trace the First Cycle Meeting

Reference
def pointer_meeting_trace(next_indices, head):
    slow = fast = head
    trace = []
    while fast != -1 and next_indices[fast] != -1:
        slow = next_indices[slow]
        fast = next_indices[next_indices[fast]]
        trace.append([slow, fast])
        if slow == fast: break
    return trace
Practice

Implement pointer_meeting_trace(next_indices, head). Return each [slow, fast] state through the first meeting or null termination. Every successor and head is a valid list index or -1; -1 represents null.

Public tests

  • Stop at collision or null

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace the First Cycle Meeting

def pointer_meeting_trace(next_indices, head):
    slow = fast = head
    trace = []
    while fast != -1 and next_indices[fast] != -1:
        slow = next_indices[slow]
        fast = next_indices[next_indices[fast]]
        trace.append([slow, fast])
        if slow == fast: break
    return trace

Follow Three Advances into a Collision

The adjacent Lab receives next_indices [1, 2, 4, 2, 3] and head 0. The reachable cycle is 2 → 4 → 3 → 2; its first collision is index 4.

Step Executed statement State Why
Start slow = fast = head slow=0, fast=0, trace=[] Initial equality is not a detected cycle.
First slow step slow = next_indices[slow] slow=1 Slow follows one successor from the head.
First fast steps fast = next_indices[next_indices[fast]]; trace.append([slow, fast]) fast=2, trace=[[1,2]] Fast follows 0 → 1 → 2 before the state is recorded.
Second advance slow = next_indices[slow]; fast = next_indices[next_indices[fast]]; trace.append([slow, fast]) slow=2, fast=3, trace=[[1,2],[2,3]] The runners have entered the cycle but are not yet equal.
Third advance slow = next_indices[slow]; fast = next_indices[next_indices[fast]]; trace.append([slow, fast]) slow=4, fast=4, trace=[[1,2],[2,3],[4,4]] The faster runner closes its relative gap inside the cycle.
Stop at collision if slow == fast: break meeting=4; cycle entry is 2 The equality certifies a cycle, while entry recovery remains a separate task.
Print Output
print(pointer_meeting_trace([1, 2, 4, 2, 3], 0)) [[1, 2], [2, 3], [4, 4]]

Recover the Entry with Equal Speeds

The first collision may occur anywhere in the cycle. If the tail length is a, slow traveled t=a+b and fast traveled 2t; their meeting implies t is a multiple of the cycle length. A runner reset to head takes a steps to the entry. The meeting runner taking those same a steps travels a+b=t positions from the entry, also returning to the entry. This proves the second phase instead of guessing that the collision was the answer.

Find the Cycle Entry

Reference
def cycle_entry_index(next_indices, head):
    slow = fast = head
    while fast != -1 and next_indices[fast] != -1:
        slow = next_indices[slow]
        fast = next_indices[next_indices[fast]]
        if slow == fast:
            finder = head
            while finder != slow:
                finder = next_indices[finder]
                slow = next_indices[slow]
            return finder
    return -1
Practice

Implement cycle_entry_index(next_indices, head). Return the cycle entry using Floyd's two phases, or -1 for an acyclic chain. Every successor and head is a valid list index or -1; -1 represents null.

Public tests

  • Recover entry after meeting

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find the Cycle Entry

def cycle_entry_index(next_indices, head):
    slow = fast = head
    while fast != -1 and next_indices[fast] != -1:
        slow = next_indices[slow]
        fast = next_indices[next_indices[fast]]
        if slow == fast:
            finder = head
            while finder != slow:
                finder = next_indices[finder]
                slow = next_indices[slow]
            return finder
    return -1

Choose What History You Need

A visited set is simpler when the actual path or first repeated state must be retained and O(n) space is acceptable. Floyd applies to deterministic transitions and needs only O(1) working state. The trace Lab deliberately stores observations, so it has O(n) output storage. A midpoint variant uses similar speeds but assumes an acyclic chain and a chosen even-length convention; it is not the operation taught by these cycle Labs.

Explain the Two Cycle Phases in an Interview

First explain the sentinel guard, then the collision argument, and finally the reset phase. Find the Duplicate Number(opens in a new tab) makes array values into successor links; its input constraints must justify that model. Practice both an acyclic chain and a cycle whose entry differs from its meeting point before adapting the pattern.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Fast and slow pointers

Hare runs two, tortoise walks one; if they meet, there is a loop.

You need to detect a cycle or find the middle of a sequence in O(1) extra space.

Trigger words

  • linked list cycle
  • cycle entry
  • middle of the list
  • happy number
  • duplicate + read-only array
def has_cycle(head):
    slow = head
    fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Spot it when

  • Cycle in a linked list.
  • Middle node.
  • A sequence that may repeat (happy number).

Remember

  • Check fast and fast.next before taking two steps.
  • When fast reaches the end, slow is in the middle.

How problems bend it

  • Middle node: Return slow after the loop ends.
  • Where the cycle starts: After they meet, move one pointer back to the head; step both one at a time until they meet again.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Cycle detection and entry recoveryO(n)O(n)n is the number of reachable distinct indices; the tail and cycle are each traversed only a constant number of times.

Space

O(1) working space for entry recovery; the meeting trace returns O(n) states.

Assumptions

  • Indices must name a valid successor or -1. A meeting node is not necessarily the cycle entry, and the detection loop does not identify a chain midpoint.
  • Python list[-1] reads the last element rather than representing null; test the sentinel before each two-step dereference.

Invariants Worth Saying Aloud

  1. After t completed detection iterations, slow has taken t successor steps and fast has taken 2t steps from head.
  2. A collision is tested after advancing; termination -1 is checked before it is used as a list index.

When To Use Or Avoid Fast and Slow Pointers

Use It When

  • Detect repetition in a deterministic successor chain without storing every visited state.
  • Find a cycle entry after proving the first collision and resetting one runner.

Choose Another Tool When

  • Use a visited set when recording the path or first repeated state matters more than constant working space.
  • Use graph traversal for branching adjacency: a node with multiple choices does not define the successor relation required by Floyd.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Dereferencing the null sentinel

Using -1 as a Python index silently reads the final array entry and can create a fictitious successor.

Prevent it: Test fast != -1 before indexing and test its successor before a second step.

Avoid

next_fast = next_indices[fast]

Use instead

next_fast = -1 if fast == -1 else next_indices[fast]

Calling initial equality a cycle

Slow and fast start at the same head even for an acyclic two-node chain; checking equality immediately produces a false cycle report.

Prevent it: Move the guarded runners first and compare the resulting positions.

Avoid

has_cycle = slow == fast

Use instead

slow = next_indices[slow]
fast = next_indices[next_indices[fast]]
has_cycle = slow == fast

Returning the meeting point as the entry

For successor links [1, 2, 3, 1], the meeting at 3 differs from the entry at 1. Starting both recovery runners at the meeting ends immediately with the wrong index.

Prevent it: Reset one runner to head and advance it alongside slow one successor at a time.

Avoid

finder = slow

Use instead

finder = head
while finder != slow:
    finder = next_indices[finder]
    slow = next_indices[slow]

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.