Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (finding the intersection node of two linked lists by switching heads)

What is printed? (finding the intersection node of two linked lists by switching heads)
class N:
    def __init__(s, v, n=None): s.v, s.n = v, n
common = N(8, N(4, N(5)))
a = N(4, N(1, common))
b = N(5, N(6, N(1, common)))
p, q, steps = a, b, 0
while p is not q:
    p = p.n if p else b
    q = q.n if q else a
    steps += 1
print(p.v, steps)
  1. A. 8 9
  2. B. 1 9
  3. C. 8 5
  4. D. 8 11

Correct answer: A. 8 9

Each pointer walks its own list, takes one step onto None, then restarts at the head of the other list, so both cover the same distance before meeting at the first shared node: (5 + 1) + 3 = 9 steps for p and (6 + 1) + 2 = 9 for q. They meet at the node with value 8 – the two nodes with value 1 are different objects, which is why identity (is), not ==, is compared. O(m + n), O(1) space.

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

Exams that ask this topic