Given two singly linked lists, write a function to find the node at which the two lists intersect. If the lists do not intersect, return null. Two linked lists intersect if they share the exact same node, not just nodes with equal values. You can assume there are no cycles within either linked list.
For example:
List A: 3 -> 7 -> 8 -> 10 List B: 99 -> 1 -> 8 -> 10 Intersection: Node with value 8
List A: 2 -> 6 -> 4 List B: 1 -> 5 Intersection: null
List A: 1 -> 9 -> 1 -> 2 -> 4 List B: 3 -> 2 -> 4 Intersection: Node with value 2
List A: 4 -> 1 -> 8 -> 4 -> 5 List B: 5 -> 6 -> 1 -> 8 -> 4 -> 5 Intersection: Node with value 8
Your function should have the following signature:
python def getIntersectionNode(headA, headB): # write your code here pass
Here's how to find the intersection node of two linked lists. I'll start with a brute-force approach and then move on to a more efficient solution.
The most straightforward approach is to iterate through each node of the first linked list and, for each node, iterate through the second linked list to see if we find a matching node (same memory address). If we find a match, that's our intersection node.
O(m*n), where 'm' is the length of the first linked list and 'n' is the length of the second linked list. This is because, in the worst case, we compare every node in the first list to every node in the second list.
O(1). We're not using any extra space; we're just comparing nodes.
python def get_intersection_node_brute_force(headA, headB): current_a = headA while current_a: current_b = headB while current_b: if current_a == current_b: return current_a current_b = current_b.next current_a = current_a.next return None
A more efficient solution involves these steps:
O(m + n), where 'm' and 'n' are the lengths of the two linked lists. We iterate through each list at most once (or twice, depending on how you count finding the lengths).
O(1). We're only using a few extra variables to store lengths and pointers; the space used doesn't scale with the input size.
python def get_intersection_node(headA, headB): lenA = 0 lenB = 0 currA = headA currB = headB
# Find lengths of the lists
while currA:
lenA += 1
currA = currA.next
while currB:
lenB += 1
currB = currB.next
currA = headA
currB = headB
# Move the pointer of the longer list forward
if lenA > lenB:
for _ in range(lenA - lenB):
currA = currA.next
elif lenB > lenA:
for _ in range(lenB - lenA):
currB = currB.next
# Traverse both lists until intersection is found
while currA and currB:
if currA == currB:
return currA
currA = currA.next
currB = currB.next
return None
None
).None
.The optimal solution works by aligning the two lists such that if they intersect, they will do so at the same distance from their respective current pointers. By first finding the lengths and then advancing the pointer of the longer list, we ensure that when we iterate through them simultaneously, we'll hit the intersection point at the same time (if one exists).