Detect intersection of two linked lists
Company: LinkedIn
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates a candidate's ability to manipulate singly linked lists, reason about pointer and reference equality between nodes, and perform algorithmic analysis of time and space trade-offs.
Constraints
- 0 <= len(prefixA), len(prefixB) <= 30000
- 0 <= len(sharedTail) <= 30000
- An empty sharedTail means the two lists do not intersect.
- Node values fit in a 32-bit signed integer.
- Nodes are compared by reference (identity), not by value.
- Target O(m + n) time and O(1) extra space.
Examples
Input: ([1, 2, 3], [6, 7], [4, 5])
Expected Output: 4
Explanation: List A is 1->2->3->4->5 and list B is 6->7->4->5; they merge at the node with value 4, which is the first shared node.
Input: ([1, 9, 1], [3], [2, 4])
Expected Output: 2
Explanation: List A is 1->9->1->2->4 and list B is 3->2->4; the shared tail starts at value 2, so the first intersection node is 2.
Hints
- Comparing nodes by value is wrong: two lists can contain identical values yet never share a physical node. You must compare by node identity.
- If the lists have lengths m and n, the part after the intersection has the same length for both. The difference m - n comes entirely from the unique prefixes.
- Two-pointer trick: walk pointer A through list A then continue into list B, and pointer B through list B then into list A. Both travel m + n steps, so they align at the first shared node — or both hit null together when there is no intersection.
- Handle the empty-list case first: if either reconstructed list is empty, there can be no intersection.