Problem Description
Given the heads of two singly linked lists headA and headB, return the node at which the two lists intersect. If the linked lists have no intersection, return null. Note that the intersection is defined by reference, not by value.
Key Insights
- The intersection point is defined by reference (i.e., the same memory location), not by the node value.
- Using two pointers that traverse both lists can help align the pointers so they traverse an equal number of nodes.
- When one pointer reaches the end of its list, it switches to the head of the other list.
- If the linked lists intersect, the pointers will eventually meet at the intersection node; if not, both will become null.
Space and Time Complexity
Time Complexity: O(m + n)
Space Complexity: O(1)
Solution
We use a two-pointer approach. Initialize two pointers, one at headA and one at headB. Traverse the lists by moving each pointer one step at a time. When a pointer reaches the end of its list, reset it to the head of the other list. This aligns the pointers so that if there is an intersection, they will meet at the intersecting node. If not, both pointers will eventually become null, indicating no intersection. This approach runs in O(m + n) time and uses constant extra space.