Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP

Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle length)?

Floyd's cycle detection on a list whose last node links back into the list. What does this print (meeting value, cycle-start value, cycle length)?
h = build([60, 73, 28, 96, 31, 84, 81, 54])
t = h
while t.nx: t = t.nx
p = h
for _ in range(3): p = p.nx
t.nx = p
s = f = h
while True:
    s, f = s.nx, f.nx.nx
    if s is f: break
meet = s.v
s = h
while s is not f: s, f = s.nx, f.nx
start = s.v
n, q = 1, s.nx
while q is not s: q, n = q.nx, n + 1
print(meet, start, n)
  1. A. 84 96 5
  2. B. 84 84 5
  3. C. 84 96 6
  4. D. 96 84 5

Correct answer: A. 84 96 5

After the first meeting, moving one pointer back to the head and stepping both one node at a time makes them meet at the cycle's entry (distance-to-start = distance-from-meeting mod cycle length). Output: 84 96 5.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic