easyDSA

How do you find the intersection node of two linked lists?

877 views
01

Understand the problem

Explain the two-pointer length-equalizing trick.

linked-listtwo-pointers
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Two-pointer switch
Run Playground
class ListNode:
    def __init__(self, val, nxt=None):
        self.val, self.next = val, nxt

def get_intersection(headA, headB):
    a, b = headA, headB
    while a is not b:
        a = a.next if a else headB
        b = b.next if b else headA
    return a            # node or None


# --- demo ---  both lists share the tail 8->4->5
shared = ListNode(8, ListNode(4, ListNode(5)))
headA = ListNode(4, ListNode(1, shared))            # 4->1->8->4->5
headB = ListNode(5, ListNode(6, ListNode(1, shared)))  # 5->6->1->8->4->5
node = get_intersection(headA, headB)
print(node.val if node else None)   # 8
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.