PPractick

DSA interview question

Intersection Point of Two Linked Lists (Y-Shaped)

Medium · Data structures · Topics: linkedlist, two pointer

The problem

Two delivery routes are stored as singly linked lists of stops, and at some stop they merge into the same physical chain of nodes, forming a Y shape. The routing system needs the first shared node (the node itself, not just an equal value), or nullptr if the routes never meet. A hash set of one list's nodes works in O(m) memory. The elegant O(1)-memory trick walks two pointers and, when one reaches the end, restarts it at the other list's head. After at most one switch each, both have walked the same total distance and arrive at the intersection together.

Example: A = 4 -> 1 -> 8 -> 4 -> 5, B = 5 -> 6 -> 1 -> 8 -> 4 -> 5, sharing 8 -> 4 -> 5 → the node with value 8.

Function signature

Node* getIntersectionNode(Node* headA, Node* headB);  // first shared node, or nullptr

Test cases

Input (A-only part, B-only part, shared part)OutputExplanation
([4, 1], [5, 6, 1], [8, 4, 5])node 8The equal value 1 is not shared: only node identity counts
([1, 9, 1], [3], [2, 4])node 2
([2, 6, 4], [1, 5], [])nullptrNo shared part
([], [], [7])node 7Both lists are the same list
([1, 2, 3], [], [4])node 4B starts at the shared part

(Confirm: the lists are acyclic and unmodified; intersection means the same node in memory, not equal values.)

How interviewers phrase it

Clarifying questions to ask

  1. Does intersection mean the same node, or equal values? (Same node.)
  2. Can the lists have cycles? (Assume not.)
  3. Can I modify the lists?

Follow-ups to expect

  1. "Why does switching heads work?"
  2. "What's the length-difference approach?"
  3. "What's the hash-set approach?"
  4. "What if there's no intersection?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in