← All Exercises

Find the Merge Base of Two Branches

intermediatejavascript~25min

Background

Rebases and cherry-picks go wrong when the shared ancestor is assumed rather than computed. Walking the DAG makes the plan auditable.

Problem

Given commits with parent links and two branch heads, return the merge base and each branch's unique commits so a rebase plan is explicit.

Input

JSON object: { commits: [{ hash, parents: string[] }], headA, headB }

Output

JSON object: { mergeBase, onlyA: string[], onlyB: string[] }

Sample tests

Sample 1

Input: {"commits":[{"hash":"a1","parents":["base"]},{"hash":"b1","parents":["base"]},{"hash":"base","parents":[]}],"headA":"a1","headB":"b1"}
Expected: {"mergeBase":"base","onlyA":["a1"],"onlyB":["b1"]}

Sample 2

Input: {"commits":[{"hash":"x1","parents":["x0"]},{"hash":"x0","parents":["base"]},{"hash":"base","parents":[]}],"headA":"x1","headB":"x0"}
Expected: {"mergeBase":"x0","onlyA":["x1"],"onlyB":[]}

Your solution

Learning objective

Read Git history as a DAG instead of a line of commits.