Data Structures & AlgorithmsVery hardTCS NQT · Amazon coding round

In a linked list the first 5 nodes form a tail, and the next 7 nodes form a cycle (the last node points back to the 6th node). Floyd's algorithm starts with slow and fast pointers both at the head; each iteration moves slow by one node and fast by two, and then compares them. After how many iterations are they first equal?

  1. A. 5
  2. B. 7
  3. C. 12
  4. D. 14

Correct answer: B. 7

Once both pointers are in the cycle, fast gains one node per step on slow. They meet at the first iteration t that is at least the tail length 5 and a multiple of the cycle length 7, giving t = 7 (and not tail + cycle = 12).

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

Exams that ask this topic