Intersection of Two Linked Lists
Find the node at which two singly linked lists intersect in O(n + m) time and O(1) space by switching list heads upon reaching null.
01The 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.
The judge guarantees that there are no cycles anywhere in the entire linked structure.
Note that the linked lists must retain their original structure after the function returns.
Can you write a solution that runs in O(m + n) time and uses only O(1) memory?
| Input | Output | Why |
|---|---|---|
listA = [4, 1, 8, 4, 5], listB = [5, 6, 1, 8, 4, 5], shared is 8 | Node(8) | Lists merge into shared tail starting at node 8 |
listA = [1, 9, 1, 2, 4], listB = [3, 2, 4], shared is 2 | Node(2) | Lists intersect at node 2 |
listA = [2, 6, 4], listB = [1, 5], no intersection | null | Lists do not intersect |
Constraints: 1 to 30,000 nodes per list, values between 1 and 100,000, no cycles.
Loading the rest of the lesson…