SDE & MLE Prep

160. Intersection of Two Linked Lists

Problem

Two singly linked lists may merge at some node and share every node after it. Return the first shared node, or null if they never meet. Keep both lists unchanged.

Example: 4→1→8→4→5 and 5→6→1→8→4→5, sharing from the node 8 → that node

Constraints: follow-up: O(m + n) time and O(1) memory.

Walk a over A then B, b over B then A. Both travel lenA + lenB steps, so they meet at the intersection (or both reach null together).

Complexity: O(m + n) time, O(1) space.

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        a, b = headA, headB
        while a is not b:
            a = a.next if a else headB
            b = b.next if b else headA
        return a