Find Intersection Point

Find the intersection point of two Y-shaped linked lists

Read Here
Step0 / 10
PhaseInitialize
List A4
List B3
Back To Linked List

Code

1def getIntersectionNode(headA, headB):
2 # Calculate lengths of both lists
3 lenA, lenB = 0, 0
4 currA, currB = headA, headB
5
6 while currA:
7 lenA += 1
8 currA = currA.next
9
10 while currB:
11 lenB += 1
12 currB = currB.next
13
14 # Reset pointers to heads
15 currA, currB = headA, headB
16
17 # Move the longer list's pointer ahead
18 if lenA > lenB:
19 for _ in range(lenA - lenB):
20 currA = currA.next
21 elif lenB > lenA:
22 for _ in range(lenB - lenA):
23 currB = currB.next
24
25 # Move both pointers together
26 while currA and currB:
27 if currA == currB:
28 return currA
29 currA = currA.next
30 currB = currB.next
31
32 return None
Function definition

Linked Lists

INIT LISTS

Step

0 / 10

Phase

Initialize

Diff

0

List A

null1next2next3next4nextcurr

List B

null5next6next4nextcurr

Progress

Processing

Searching for intersection point...

Pointer State

Pointers

pointerA

1

pointerB

5

lengthA

0

lengthB

0

Key Insight

Calculate lengths first, then align pointers to the same starting position before advancing both together.

Explanation

Init

Initialize Pointers

Set up pointers for both linked lists.