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([93, 63, 96, 30, 16, 91, 88, 71, 62, 18])
t = h
while t.nx: t = t.nx
p = h
for _ in range(1): 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. 18 63 9
  2. B. 18 18 9
  3. C. 63 18 9
  4. D. 18 63 10

Correct answer: A. 18 63 9

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: 18 63 9.

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

Exams that ask this topic