Question presented to candidate: "You are given the head of a singly linked list that may contain a cycle. Return the node where the cycle begins, or None if there is no cycle. Can you do it without extra memory? Please write it in Python."
What a strong answer should cover:
- A hash-set baseline (first node seen twice is the entry), O(n) time and O(n) space.
- Floyd's tortoise and hare: slow moves 1, fast moves 2; when they meet, restart one pointer at the head and move both by 1 until they meet at the entry.
- Why phase 2 works: the meeting distance is a multiple of the cycle length, so mu more steps from the meeting point land on the entry. O(n) time, O(1) space.
- Edge cases: empty list, single node with and without a self-loop, cycle back to the head, duplicate values.
- Python specifics: compare nodes with
is, not==; a plain class hashes by identity soset()works, but a@dataclassnode defines__eq__and becomes unhashable.
Clarifying questions expected:
- "Return the node, or an index? What if there is no cycle?"
- "Is O(n) extra memory allowed, and may I modify the list?"
Code / implementation expected: Yes โ detect_cycle(head) in Python with two pointers and no extra data structures.