Intersection of Two Linked Lists

Problem Summary

(Write in your own words, not copied from LeetCode. This forces comprehension.)

Why This Works

(Explain the core reason the solution is correct.)

Main Concepts Used

(Mark the CS concepts or algorithms used.)

Time & Space Complexity

Code

class Solution:
    def getIntersectionNode(
        self, headA: ListNode, headB: ListNode
    ) -> Optional[ListNode]:
        nodesOfA = set()

        cur = headA
        while cur:
            nodesOfA.add(cur)
            cur = cur.next

        cur = headB
        while cur:
            if cur in nodesOfA:
                return cur
            cur = cur.next

        return None

Optimized Time & Space Complexity

Why This Works

(Explain the core reason the solution is correct.)

Optimized Code

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        lenghtA = 0 # 5
        cur = headA
        while cur:
            lenghtA += 1
            cur = cur.next

        lenghtB = 0 # 6 
        cur = headB
        while cur:
            lenghtB += 1
            cur = cur.next

        newHead = None
        diff = abs(lenghtA - lenghtB) # 1
        newHead = headA if lenghtA > lenghtB else headB
        for _ in range(diff):
            newHead = newHead.next
        headA = newHead if lenghtA > lenghtB else headA
        headB = newHead if lenghtB > lenghtA else headB
        
        while headA and headB:
            if headA == headB:
                return headA
            headA = headA.next 
            headB = headB.next 
        return None