Algo-Sim › Linked Lists
Intersection of Two Linked Lists
Easy · Linked Lists · step through it in Java, Python and C++ on your own input
Two pointers that restart on the other list when they fall off the end both walk m + n nodes and meet on the first shared node.
Problem
Two singly linked lists start at headA and headB. They may merge at some node and share every node from there on (the same nodes, not copies with equal values). Return the first shared node, or null if the lists never meet. Neither list may be changed, and there are no cycles.
Constraints
- 1 ≤ m, n ≤ 3 · 10⁴ nodes
- 1 ≤ Node.val ≤ 10⁵
- Follow-up: O(m + n) time and O(1) extra space
Edge cases to test
- No intersection: both reach null together
- Intersecting at the first node
- Very different lengths
Follow-up questions
- Why do the pointers meet?
- Each walks a + c + b nodes in total (its own part, the shared part, the other’s part), so they line up on the first shared node or on null.
- What is the length-based alternative?
- Compute both lengths, advance the longer list by the difference, then walk together: same O(m + n), O(1).
Solution
Java
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;
}Python
def get_intersection_node(headA, headB):
a, b = headA, headB
while a is not b:
a = headB if a is None else a.next
b = headA if b is None else b.next
return aC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *a = headA, *b = headB;
while (a != b) {
a = (a == nullptr) ? headB : a->next;
b = (b == nullptr) ? headA : b->next;
}
return a;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)
- Reverse Nodes in k-Group (Hard)