Pages

110 Intersection of Two Linked Lists - Return intersecting node

Given: Heads of two singly linked lists.
Return: The node where the two lists intersect (by reference), or None if they don’t intersect.

How It Works:

  • Two pointers start at headA and headB.

  • When a pointer reaches the end of its list, it switches to the head of the other list.

  • If the two lists intersect, they’ll meet at the intersection node.

  • If not, both will end up as None at the same time.

Time & Space Complexity:

  • Time: O(m + n)

  • Space: O(1)


def find_intersecting(heada,headb):

    if not heada or not headb:
        return None

    currentA = heada
    currentB = headb
    while  currentA != currentB:
        if currentA:
            currentA = currentA.next 
        else:
            currentA = headb

        if currentB:
            currentB = currentB.next
        else:
            currentB = heada
    return currentA  # Either the intersecting node or None

How It Works:

  • ptrA and ptrB are two pointers, initially starting at headA and headB respectively.

  • They traverse the lists node by node.

  • When a pointer reaches the end of its list, it is redirected to the start of the other list.

  • This ensures that both pointers travel the same total distance, and thus will meet at the intersection point — or both become None if no intersection.


List A:       A1 → A2
                       ↘
                         C1 → C2 → C3
                       ↗
List B: B1 → B2 → B3