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), thefast is not None and fast.next is not Noneorder, and asetas 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.