Skip to the solution
EasyDSA11 min read

What is the fast and slow pointer technique?

948 views

The problem

Question presented to candidate: "What is the fast and slow pointer technique? Explain how it works and show me, in Python, two problems it solves on a linked list."

What a strong answer should cover:

  • Two pointers start at the same place; the slow one moves one step and the fast one moves two steps per round.
  • Use 1, the middle: when the fast pointer reaches the end, the slow pointer is halfway.
  • Use 2, cycles (Floyd's algorithm): inside a loop the fast pointer gains one node per round, so the two must meet; if the fast one reaches the end, there is no cycle.
  • O(n) time and O(1) extra space, compared with O(n) space for a hash set of visited nodes.
  • It also works on any sequence where each value determines the next (happy numbers, find the duplicate number).
  • Python specifics: comparing nodes with is (not == or values), the fast is not None and fast.next is not None order, and a set as the O(n)-space alternative.

Code / implementation expected: Optional โ€” a short Python function for the middle or for cycle detection; the explanation of why the pointers meet matters more.

  • dsa
  • linked-list
  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 9 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMiddle of a list and cycle detection with one pattern
PythonFast and slow pointers on a number sequence (happy numbers)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 6 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

What is a graph, and how do you represent it?

Continue