Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

List A has a nodes before it joins a shared tail of c nodes; list B has b nodes before the same tail, with a ≠ b. Pointer p walks A and, at its end, jumps to B's head; q walks B and then jumps to A's head; both move one node per step. Where do p and q first point to the same node?

  1. A. At the first shared node, after each has passed max(a, b) + c nodes
  2. B. At the first shared node, after each has passed a + b + c nodes
  3. C. At the last node of the shared tail
  4. D. Nowhere: with a ≠ b they stay out of step forever

Correct answer: B. At the first shared node, after each has passed a + b + c nodes

p passes a + c nodes of A and then b nodes of B; q passes b + c and then a. Both totals are a + b + c, so they arrive at the junction together, and since a ≠ b they cannot coincide earlier. If the lists do not intersect, both reach null together instead.

More Coding Interview Problems questions

Exams that ask this topic