Find the Intersection of Two Linked Chains
Company: C3 AI
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Overview: Find the first shared node of two acyclic linked chains using node identity and constant extra space. Practice the pointer-switching technique for unequal path lengths.
Read the full C3 AI Data Scientist interview experience this question came from
Constraints
- 0 <= next_node.length <= 200000
- next_node[i] is -1 or a valid index in next_node
- head_a and head_b are each -1 or valid indices
- The chains reachable from both heads are acyclic
Examples
Input: ([1, 2, -1, 2], 0, 3)
Expected Output: 2
Explanation: The source example's chains first share node index 2.
Input: ([1, -1, 3, -1], 0, 2)
Expected Output: -1
Explanation: The source example's two chains are disjoint.
Hints
- Use one pointer per chain without storing visited nodes.
- When a pointer reaches -1, continue it from the other head so both pointers cover equal combined path lengths.