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 None if 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

4 1 5 0 1 8 4 5 List A List B Intersection

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.

Updated on: 2026-03-25T07:16:49+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements