DSA interview question
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.
Node* getIntersectionNode(Node* headA, Node* headB); // first shared node, or nullptr
| Input (A-only part, B-only part, shared part) | Output | Explanation |
|---|---|---|
([4, 1], [5, 6, 1], [8, 4, 5]) | node 8 | The equal value 1 is not shared: only node identity counts |
([1, 9, 1], [3], [2, 4]) | node 2 | |
([2, 6, 4], [1, 5], []) | nullptr | No shared part |
([], [], [7]) | node 7 | Both lists are the same list |
([1, 2, 3], [], [4]) | node 4 | B starts at the shared part |
(Confirm: the lists are acyclic and unmodified; intersection means the same node in memory, not equal values.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in