Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Intersection of Two Linked Lists in Python
When two linked lists share common nodes, we need to find their intersection point. The intersection occurs where both lists reference the same node object, not just nodes with the same value.
Given two linked lists A and B, we return the reference to the first common node. If there's no intersection, we return None.
Algorithm
We use a hash map to track visited nodes from the first list, then check if any node from the second list exists in our map ?
- Create a dictionary to store nodes from list A
- Traverse list A and add each node to the dictionary
- Traverse list B and check if each node exists in the dictionary
- Return the first matching node, or
Noneif no intersection
Implementation
class ListNode:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Solution:
def getIntersectionNode(self, headA, headB):
"""
Find intersection point of two linked lists
:type headA, headB: ListNode
:rtype: ListNode
"""
visited = {}
# Store all nodes from list A
while headA:
visited[headA] = True
headA = headA.next
# Check if any node from list B exists in visited
while headB:
if headB in visited:
return headB
headB = headB.next
return None
# Create intersection point
intersect = ListNode(8, ListNode(4, ListNode(5)))
# Create list A: [4, 1] ? intersection
headA = ListNode(4)
headA.next = ListNode(1, intersect)
# Create list B: [5, 0, 1] ? intersection
headB = ListNode(5)
headB.next = ListNode(0, ListNode(1, intersect))
solution = Solution()
result = solution.getIntersectionNode(headA, headB)
if result:
print(f"Intersection at node with value: {result.data}")
else:
print("No intersection found")
Intersection at node with value: 8
Visual Representation
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(m + n) | Traverse both lists once |
| Space | O(m) | Store nodes from first list |
Where m and n are the lengths of the two linked lists.
Alternative Approach: Two Pointers
A space-efficient solution uses two pointers that traverse both lists ?
def getIntersectionNodeTwoPointers(self, headA, headB):
if not headA or not headB:
return None
ptrA, ptrB = headA, headB
while ptrA != ptrB:
ptrA = ptrA.next if ptrA else headB
ptrB = ptrB.next if ptrB else headA
return ptrA
Conclusion
The hash map approach provides an intuitive O(m + n) solution with O(m) space. The two-pointer technique achieves the same time complexity with O(1) space, making it more memory-efficient for large lists.
