
Problem
Solution
Submissions
Intersection of Two Linked Lists
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to find the node at which the intersection of two singly linked lists begins. 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:
A: a1 → a2 → c1 → c2 → c3 ↗ B: b1 → b2 → b3
Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.
Example 1
- Input:
- List A: 4 → 1 → 8 → 4 → 5
- List B: 5 → 6 → 1 → 8 → 4 → 5
- Output: Reference to the node with value 8
- Explanation:
- The two lists have an intersection starting at the node with value 8.
- After the intersection point, both lists share the same nodes (8 → 4 → 5).
- Return the reference to the node with value 8.
Example 2
- Input:
- List A: 1 → 9 → 1 → 2 → 4
- List B: 3 → 2 → 4
- Output: Reference to the node with value 2
- Explanation:
- The two lists have an intersection starting at the node with value 2.
- After the intersection point, both lists share the same nodes (2 → 4).
- Return the reference to the node with value 2.
Constraints
- The number of nodes of both lists is in the range [0, 10^4]
- -10^9 <= Node.val <= 10^9
- Both lists must be traversed at most once
- Time Complexity: O(n+m) where n and m are the lengths of the two lists
- Space Complexity: O(1) - no extra space should be used except for a few pointers
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Consider the lengths of both lists
- If two pointers traverse both lists, how can they be synchronized to meet at the intersection?
- You can align the pointers by accounting for the difference in list lengths
- A two-pointer technique where each pointer traverses both lists can help
- Think about what happens if both pointers start at different heads but traverse the same total distance