Find Best Merge Bases Between Two Branches in a Commit Graph
Last updated: November 29, 2026
Quick Overview
Given a commit graph as a map from commit id to its parent ids, return every best common ancestor of two commits: a commit reachable from both that is not itself an ancestor of another common ancestor. This is what git uses as the merge base, and criss-cross histories can have more than one.
GitHub
November 29, 20260
0
0 solved
Given a commit graph as a map from commit id to its parent ids, return every best common ancestor of two commits: a commit reachable from both that is not itself an ancestor of another common ancestor. This is what git uses as the merge base, and criss-cross histories can have more than one.
GitHub computes merge bases constantly to render pull request diffs and the ahead/behind counts on branches. In an onsite coding round the interviewer checks that you treat history as a DAG rather than a tree, handle merge commits with two parents, and recognize that there can be several answers.
What the Interviewer Expects
- Recognizes the history is a DAG, so tree LCA techniques do not apply directly
- Computes ancestor sets of both commits with BFS
- Filters out common ancestors dominated by another common ancestor
- Handles criss-cross merges returning multiple bases
- Explains cost and how real systems bound it (generation numbers, commit-graph files)
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
- Repositories have millions of commits. How do generation numbers let you stop the walk early?
- How would you compute the ahead/behind counts shown on a branch list from this?
- When there are two merge bases, how does git produce a single base for a three-way merge?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
Input: parents: dict[commit, list[commit]] (root has none, merges have two or more), and commits a, b. A commit counts as its own ancestor, so if a is an ancestor of b, the answer is a. Ou...
High-Level Design
- BFS from
aover parent edges to get its ancestor set, same forb. commonis the intersection.- A common commit is not best if it is a proper ancestor of another common commit. Every such...