Space
Open
From Fieldwork
Scales
Archive
Imagine the lists look like this:
[non-shared A] + [shared][non-shared B] + [shared]If you conceptually concatenate the two lists, you create two paths of equal length:
[non-shared A] $\to$ [shared] $\to$ [non-shared B] $\to$ [shared][non-shared B] $\to$ [shared] $\to$ [non-shared A] $\to$ [shared]By switching pointers to the head of the other list once they hit the end, both pointers will travel exactly len(A) + len(B) nodes. Because the total distance is now the same, they align perfectly at the intersection node.
If there is no intersection, both pointers will traverse List A and then List B (and vice versa) and finally become None at the exact same time. The loop while pA != pB terminates because None == None, and None is returned.
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 pA reaches the end of list A, redirect it to the head of list B
# Otherwise, move to the next node
pA = headB if pA is None else pA.next
# If pB reaches the end of list B, redirect it to the head of list A
# Otherwise, move to the next node
pB = headA if pB is None else pB.next
# Either they meet at the intersection node, or they meet at None (no intersection)
return pAPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode