160. Intersection of Two Linked Lists

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.



Note: Has an easy solution, but O(N) good solution is Medium.
a + c + b = b + c + a

Diagram showing that one pointer could go over a + c + b while the other goes over b + c + a, and then both will end up on the intersection node.



def getIntersectionNode(headA: ListNode, headB: ListNode):
       
    pA = headA
    pB = headB

    while pA != pB:
        pA = headB if pA is None else pA.next
        pB = headA if pB is None else pB.next

    return pA
    # Note: In the case lists do not intersect, the pointers for A and B
    # will still line up in the 2nd iteration, just that here won't be
    # a common node down the list and both will reach their respective ends
    # at the same time. So pA will be NULL in that case

Comments

Popular posts from this blog

849. Maximize Distance to Closest Person

347. Top K Frequent Elements

139. Word Break