Question presented to candidate: "Given the head of a linked list, tell me whether it contains a cycle, meaning some node's next pointer leads back to an earlier node. Write it in Python. Can you do it with constant extra memory?"
What a strong answer should cover:
- The simple approach: remember visited nodes in a hash set; O(n) time and O(n) space.
- Floyd's tortoise and hare: one pointer moves one step, the other two; they meet if and only if there is a cycle; O(n) time and O(1) space.
- Why they must meet: inside the loop the gap shrinks by exactly one node per round, so it cannot be skipped.
- Comparing node identity, not values, and handling the empty list, one node, and a node that points to itself.
- The follow-ups: cycle length, and where the cycle starts (reset one pointer to the head).
- Python specifics: identity with
is, why asetof nodes works with the default hash but not with a@dataclassnode, and checkingfast is not Nonebeforefast.next.
Clarifying questions expected:
- "Do you only need true or false, or also where the cycle starts?"
- "May I modify the list (for example mark visited nodes), or must it stay unchanged?"
Code / implementation expected: Yes — a Python has_cycle(head) using Floyd's algorithm, ideally after describing the hash-set version.