Drill

ProblemsJavaScript › patterns

Which commit broke the build

mediumpatternsBinary searchArraysJavaScript

Every commit up to some point built cleanly and every one after it fails. A bisect finds the first bad one without building them all.

firstBadBuild(passed: list<bool>) → int

Solve it in the editor →

Where you start

function firstBadBuild(passed) {
  
}

Worked examples

CallResult
firstBadBuild([true,true,false,false])2
firstBadBuild([true,true,true])-1
firstBadBuild([false,false])0
firstBadBuild([])-1

Hint

This is what `git bisect` does. Halve the range, and let a failure pull the right edge in while a pass pushes the left edge out.

Reference solution in JavaScript
function firstBadBuild(passed) {
  let lo = 0;
  let hi = passed.length;
  while (lo < hi) {
    const mid = Math.floor((lo + hi) / 2);
    if (passed[mid]) lo = mid + 1;
    else hi = mid;
  }
  return lo === passed.length ? -1 : lo;
}

The same problem in another language

More patterns problems in JavaScript