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
Coding & Algorithms
Software Engineer
GitHub
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Medium

0

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
graphs
BFS
DAG ancestors
git internals
set operations
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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
  1. BFS from a over parent edges to get its ancestor set, same for b.
  2. common is the intersection.
  3. A common commit is not best if it is a proper ancestor of another common commit. Every such...

Submit Your Answer
Markdown supported