Leetcode 160: Intersection of Two Linked Lists

Finding the node at which the intersection of two singly linked lists begins using the Two Pointers technique.

The original problem is here.

Hash map approach

Algorithm

My solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        map_a = {}
        node_a_now = headA
        while node_a_now:
            map_a[node_a_now] = True
            node_a_now = node_a_now.next
        node_b_now = headB
        while node_b_now:
            if node_b_now in map_a:
                return node_b_now
            node_b_now = node_b_now.next
        return None

Two Pointers Approach

Algorithm

My solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        if not headA or not headB:
            return None
            
        pA, pB = headA, headB
        
        while pA != pB:
            # If pointer reaches the end, switch to the other list's head
            # Otherwise, move to the next node
            pA = pA.next if pA else headB
            pB = pB.next if pB else headA
            
        return pA

Complexity Analysis

References