160. Intersection of Two Linked Lists
Asked at 12Amazon47Microsoft46Bloomberg45Google38Meta34Apple30TikTok26Airbnb75Wells Fargo65Samsung63LinkedIn47Goldman Sachs28
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
common = make_list([8, 4, 5])
A = make_list([4, 1]); A.next.next = common
B = make_list([5, 6, 1]); B.next.next.next = common
assert Solution().getIntersectionNode(A, B) is common
assert Solution().getIntersectionNode(make_list([1]), make_list([2])) is None
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA, b = headB;
while (a != b) {
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}
func getIntersectionNode(headA, headB *ListNode) *ListNode {
a, b := headA, headB
for a != b { // both walk lenA + lenB nodes, so they meet at the junction (or at nil)
if a != nil {
a = a.Next
} else {
a = headB
}
if b != nil {
b = b.Next
} else {
b = headA
}
}
return a
}