How would you detect a cycle in a linked list and test the solution?
Answer
Use a slow pointer that advances one node and a fast pointer that advances two. They meet if a cycle exists; reaching the end proves the list is acyclic. This uses linear time and constant extra space. Test an empty list, one node with and without a self-cycle, a cycle beginning at the head or middle, and a long acyclic list.
Strong answer includes
- explains the slow and fast pointer invariant
- states linear time and constant auxiliary space
- covers self-cycles and cycles at different positions
Practical example
A candidate's first implementation compares node values instead of node references to detect a repeat, which incorrectly flags a cycle in an acyclic list that happens to contain two nodes holding the same value; switching the comparison to pointer identity fixes it.