Data Structures & AlgorithmsVery hardAmazon · Microsoft OA

Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet and the value at the start of the cycle.

Problem: Floyd's cycle detection on a linked list whose tail points back into the middle. Report the value where slow and fast first meet and the value at the start of the cycle.
class N:
    def __init__(s, v): s.v, s.nx = v, None
nodes = [N(v) for v in [1, 2, 3, 4, 5, 6]]
for a, b in zip(nodes, nodes[1:]): a.nx = b
nodes[-1].nx = nodes[2]
slow = fast = nodes[0]
while True:
    slow, fast = slow.nx, fast.nx.nx
    if slow is fast: break
meet = slow.v
p = nodes[0]
while p is not slow: p, slow = p.nx, slow.nx
print(meet, p.v)
What is printed?
  1. A. 3 3
  2. B. 4 3
  3. C. 6 3
  4. D. 5 3

Correct answer: D. 5 3

Positions (slow, fast) go (2,3), (3,5), (4,3), (5,5): they meet at value 5. Then a pointer from the head and one from the meeting point, moving one step each, meet at the cycle start 3, because the head-to-start distance equals the meeting-point-to-start distance modulo the cycle length.

More Coding Interview Problems questions

Exams that ask this topic