Find the Shared Ancestor Commit Where Two Branch Histories Join
Last updated: November 29, 2026
Quick Overview
Two branch histories are singly linked lists of commit nodes that point to their parent, and after some commit they share the same nodes. Return the first shared node (by identity), or None if the histories never meet, using O(1) extra space.
0
0
0 solved
Two branch histories are singly linked lists of commit nodes that point to their parent, and after some commit they share the same nodes. Return the first shared node (by identity), or None if the histories never meet, using O(1) extra space.
Google interviewers like this framed around version control because the shared suffix is natural there. They want the two-pointer length-equalizing trick and a clear argument for why it terminates even when there is no intersection.
What the Interviewer Expects
- Compare nodes by identity, not by value
- Offer the hash set solution first, then improve to O(1) space
- Explain the pointer-switching trick and why both pointers travel m + n steps
- Show termination when the lists do not intersect (both reach None together)
- Do not modify the lists
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- What if the histories might contain a cycle?
- Find the join point when you can only read each list once, as a stream.
- How would you find the merge base of two branches in a real DAG with merge commits?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
- Inputs: heads
aandb; the lists may or may not share a tail. - Output: the first node common to both (same object), else None.
- No mutation, O(1) extra space....
High-Level Design
Let the lists have private parts of length p and q and a shared tail of length t. A pointer that walks a then b covers p + t + q nodes before reaching the join; one that walks b then a covers q + t + ...