Skip to the solution
EasyDSA11 min read

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

877 views

The problem

Question presented to candidate: "You get the heads of two singly linked lists. If they merge into one shared tail, return the first shared node; otherwise return None. The lists have no cycles and must not be changed. Can you do it in O(1) extra memory? Please write it in Python."

What a strong answer should cover:

  • Intersection means the same node object, not equal values; the shared part is a common tail (Y shape).
  • A hash-set baseline in O(m + n) time and O(m) space.
  • An O(1)-space answer: align by length difference, or the switch-heads two pointers that both walk a + c + b nodes.
  • Why the switch-heads loop ends with no intersection: both pointers become None on the same step.
  • Python specifics: compare with is, write the switch as pa = pa.next if pa else head_b, and remember that a plain class hashes by identity so set() holds nodes, not values.

Clarifying questions expected:

  • "Same node, or equal values?"
  • "Can the lists contain cycles, and may I modify them?"

Code / implementation expected: Yes โ€” get_intersection(head_a, head_b) in Python, O(1) space.

  • linked-list
  • two-pointers

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonSwitch-heads intersection on Y-shaped and separate lists
PythonHash set, length difference and switch heads on every small shape

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 10 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you find the missing number in 0..n?

Continue