educative.io

Educative

What if the intersection is at the first position

What is the intersection point is the first Node? the suggest solution logic doesn’t work in that case

Hi! The logic works even if the intersection is at the first node.

If the intersection point is the first node for both lists (i.e., both lists are identical), then the difference between the lengths will be 0. Therefore, we won’t move forward in any of the lists and will start comparing from the first node for both lists. Since the lists are identical, we will find the intersection at the very first node.

On the other hand, if the intersection point of two lists is the first node for one list and not for the other, like in the example below (intersection at Node 82):

29->32->82->11->NULL       length: 4
82->11->NULL               length: 2

The difference between the lengths will be calculated (4 - 2 = 2), and the head pointer for the longer list will be moved forward 2 steps until it reaches Node 82. We will then start comparing the nodes, and the intersection will be found at Node 82.