Find the Intersection of Two Linked Chains
C3 AIData Scientist · OnsiteLast updated
This problem tests the ability to detect the intersection point of two singly linked lists with constant space complexity, focusing on pointer manipulation and list traversal techniques.
Problem Statement
Given the heads of two acyclic 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.
For example, the following two linked lists begin to intersect at node c1:
- List A:
a1 -> a2 -> c1 -> c2 -> c3 - List B:
b1 -> b2 -> b3 -> c1 -> c2 -> c3
Requirements
- You must solve the problem in
O(n + m)time, wherenandmare the lengths of the two lists. - You must use
O(1)extra space (i.e., you cannot use a hash set to store visited nodes). - Your solution must not modify the original structure of the linked lists.
Function Signature
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def getIntersectionNode(headA: ListNode, headB: ListNode) -> ListNode:
pass
Examples
Example 1:
- Input:
headA = [4,1,8,4,5],headB = [5,6,1,8,4,5] - Output:
Node(8) - Explanation: The lists intersect at node with value 8.
Example 2:
- Input:
headA = [2,6,4],headB = [1,5] - Output:
null - Explanation: No intersection.
Edge Cases
- One or both lists are empty.
- The lists intersect at the very last node.
- The lists are of significantly different lengths.
Hints
Hint 1
If both lists had the same length, you could iterate through them simultaneously and find the point where the pointers match.
Hint 2
Consider what happens if you concatenate the two lists in different orders: List A + List B and List B + List A.
Hint 3
If a pointer reaches the end of its list, redirect it to the head of the other list; this naturally aligns the two pointers after at most one full traversal of both lists.
Follow-up questions
- What if the linked lists are allowed to contain cycles? How would you detect if they intersect?
- How would you modify your approach if you were required to find the intersection of three different linked lists?
- Can you solve this if you are not allowed to use the identity of the nodes (e.g., if you only have access to the values)?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.