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([18, 95, 21, 69, 42, 97, 27, 50, 45])
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. 45 45 8
  2. B. 45 95 8
  3. C. 95 45 8
  4. D. 45 95 9

Correct answer: B. 45 95 8

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: 45 95 8.

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

Exams that ask this topic