Intersection of Two Linked Lists - Problem
You're given the heads of two singly linked lists, headA and headB. Your task is to find the node where these two lists intersect and return that node. If the lists don't intersect at all, return null.
Key Point: The intersection is based on reference equality, not value equality. Two nodes are considered the same if they are the exact same node object in memory.
For example, consider these two linked lists:
List A: 4 → 1 → 8 → 4 → 5
List B: 6 → 1 → 8 → 4 → 5
↑
intersection point
The lists intersect at the node with value 8, and from that point onward, they share the same nodes.
Important constraints:
- There are no cycles in the linked structure
- The linked lists must retain their original structure after the function returns
- You cannot modify the values or structure of the nodes
Input & Output
example_1.py — Basic Intersection
$
Input:
listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
›
Output:
Intersection at node with value 8
💡 Note:
The lists intersect at the node with value 8. List A has 2 nodes before intersection, List B has 3 nodes before intersection. From the intersection point onward, both lists share the same nodes.
example_2.py — No Intersection
$
Input:
listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
›
Output:
null
💡 Note:
The two lists do not intersect at all. List A and List B are completely separate with no shared nodes, so we return null.
example_3.py — Single Node Intersection
$
Input:
listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
›
Output:
Intersection at node with value 2
💡 Note:
List A has 3 nodes before intersection [1,9,1], then intersects with List B at node 2. List B has 1 node [3] before the intersection point.
Constraints
-
The number of nodes of listA is in the range
[1, 3 * 104] -
The number of nodes of listB is in the range
[1, 3 * 104] -
1 <= Node.val <= 105 -
0 <= skipA < listA.length -
0 <= skipB < listB.length - intersectVal is 0 if listA and listB do not intersect
-
Follow up: Could you write a solution that runs in
O(m + n)time and use onlyO(1)memory?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code