Intersection of Two Linked Lists - Problem
Given the heads of two singly linked lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
Note: The linked lists must retain their original structure after the function returns.
Input & Output
Example 1 — Lists Intersect
$
Input:
listA = [4,1,8,4,5], listB = [5,6,1,8,4,5]
›
Output:
[8,4,5]
💡 Note:
The intersection starts at node with value 8. Both lists share the same tail: 8→4→5
Example 2 — No Intersection
$
Input:
listA = [2,6,4], listB = [1,5]
›
Output:
null
💡 Note:
The two linked lists have no common nodes, so return null
Example 3 — Single Node Intersection
$
Input:
listA = [3], listB = [2,3]
›
Output:
[3]
💡 Note:
Lists intersect at the single node with value 3
Constraints
- The number of nodes in listA is m
- The number of nodes in listB is n
- 1 ≤ m, n ≤ 3 × 104
- 1 ≤ Node.val ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code