Intersection of Two Linked Lists
Intersection of Two Linked Lists is a easy linked list problem solved with the miscellaneous pattern.
The best approach, optimal (two pointers that switch lists), runs in O(m + n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from hash set up.
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 merge. Compare nodes by identity, not by value.
Examples
Example 1
- Input
listA = [4, 1, 8, 4, 5], listB = [5, 6, 1, 8, 4, 5], shared tail starts at 8- Output
the node with value 8- Why
- Equal values are not enough; it must be the same node object.
Example 2
- Input
listA = [2, 6, 4], listB = [1, 5], no shared nodes- Output
null
Constraints
- Lengths from
1to3 * 10^4. - No cycles. Do not modify the lists. Follow-up: O(1) memory.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 4 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Hash set | O(m + n) | O(m) |
| Optimal (two pointers that switch lists) | O(m + n) | O(1) |
1Hash set
O(m + n)O(m)Store every node of list A; the first node of list B found in the set is the intersection.
- Add all of A's nodes to a set.
- Walk B and return the first node contained in the set.
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> seen = new HashSet<>();
for (ListNode p = headA; p != null; p = p.next) seen.add(p);
for (ListNode p = headB; p != null; p = p.next) if (seen.contains(p)) return p;
return null;
}
}class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
seen = set()
p = headA
while p:
seen.add(p)
p = p.next
p = headB
while p:
if p in seen:
return p
p = p.next
return Noneclass Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
unordered_set<ListNode*> seen;
for (ListNode* p = headA; p != nullptr; p = p->next) seen.insert(p);
for (ListNode* p = headB; p != nullptr; p = p->next) if (seen.count(p)) return p;
return nullptr;
}
};function getIntersectionNode(headA, headB) {
const seen = new Set();
for (let p = headA; p !== null; p = p.next) seen.add(p);
for (let p = headB; p !== null; p = p.next) if (seen.has(p)) return p;
return null;
}2Optimal (two pointers that switch lists)
O(m + n)O(1)Pointer a walks A then B; pointer b walks B then A. Both cover lenA + lenB nodes, so they line up at the intersection, or both reach null together if there is none.
- a = headA, b = headB.
- While a != b: a = a == null ? headB : a.next; b = b == null ? headA : b.next.
- Return a.
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;
}
}class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
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 aclass Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* a = headA;
ListNode* b = headB;
while (a != b) {
a = a == nullptr ? headB : a->next;
b = b == nullptr ? headA : b->next;
}
return a;
}
};function getIntersectionNode(headA, headB) {
let a = headA, b = headB;
while (a !== b) {
a = a === null ? headB : a.next;
b = b === null ? headA : b.next;
}
return a;
}Edge cases to test
- No intersection
- Different lengths before the shared part
- Intersection at the head of one list
Hints
Hint 1
If each pointer walks its own list and then switches to the other list, both travel lenA + lenB.
FAQ
What is the best time complexity for Intersection of Two Linked Lists?
Optimal (two pointers that switch lists) runs in O(m + n) time and O(1) extra space.
Which pattern does Intersection of Two Linked Lists use?
It is a linked list problem that uses the miscellaneous pattern. Other problems with the same pattern: Delete Node in a Linked List, Copy List with Random Pointer, Partition List.
Is there a brute force solution for Intersection of Two Linked Lists?
Yes. Hash set takes O(m + n) time and O(m) space. Store every node of list A; the first node of list B found in the set is the intersection.
Which edge cases should I test for Intersection of Two Linked Lists?
No intersection; Different lengths before the shared part; Intersection at the head of one list.