Earliest Faulty Build in Version History
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A continuous integration pipeline records whether each sequential build contains a regression in a zero-indexed boolean list bad. An entry of False indicates that build i passed verification, while True indicates that build i failed.
Once a regression enters the codebase, every subsequent build also fails. Consequently, bad consists of zero or more False values followed by zero or more True values, and False never appears after True.
Implement first_bad_version(bad) to locate and return the smallest index i such that bad[i] is True. If bad is empty or contains only False entries, return -1.
def first_bad_version(bad: list[bool]) -> int:
Examples
Example 1
Input: bad = [False, False, False, True, True, True, True]
Output: 3
Builds 0, 1, and 2 pass (False). Build 3 is the earliest build marked True, and every later build (4 through 6) remains True.
Example 2
Input: bad = [False, False, False, False]
Output: -1
All four builds pass verification, so no faulty build exists and the function returns -1.
Example 3
Input: bad = [True, True, True]
Output: 0
Build 0 already fails, making index 0 the earliest faulty build.
Constraints
0 <= len(bad) <= 1_000_000- For every pair of indices
0 <= i < j < len(bad),bad[i] == Trueimpliesbad[j] == True. - Your algorithm must run in logarithmic time
O(log n)rather than scanning the entire list on million-element inputs.
Step-by-step walkthrough
Understand the goal and what "monotonic" means
We are given a boolean list
badrepresenting a software release history from version0up tolen(bad) - 1:Falsemeans the release is good (passes tests).Truemeans the release is bad (contains the bug).
The key rule in the problem statement is that
badis monotonic (one-directional: once aTrueappears, every later entry staysTrue, soFalsenever appears afterTrue):index: 0 1 2 3 4 5 6 bad: [False, False, False, True, True, True, True] \_______good________/ \______bad forever______/ ^ earliest faulty build = index 3We want to return the smallest index where
bad[i]isTrue, or-1if no version is bad (including whenbadis completely empty[]). Becauselen(bad)can be up to1,000,000, our code should inspect only a handful of entries rather than scanning the entire list.Start with a linear scan and see why we can do much better
The simplest correct solution walks from index
0to the end and returns the firstTrueit sees:def first_bad_linear(bad: list[bool]) -> int: for i in range(len(bad)): if bad[i]: return i return -1Why isn't this enough in an interview (or in real engineering tools like
git bisect)? Because if all1,000,000versions are good — or only the last version999,999is bad — a linear scan reads all one million entries. If checking each version meant compiling and testing a real software build,1,000,000checks could take weeks, whereas exploiting theFalse ... False, True ... Trueboundary takes at most 20 checks!Key idea: jump to the middle and discard half the history
Suppose we maintain an inclusive candidate range
[left, right]of indices we have not ruled out yet, starting withleft = 0andright = len(bad) - 1, plus a variablefirst_bad = -1holding the earliest bad index we have discovered so far.When we inspect the middle index
mid = (left + right) // 2, only two outcomes are possible:Case 1: bad[mid] is True [ ... ? ... | True | True, True, True ] left mid right -> mid might be the answer! Save first_bad = mid, then search ONLY left .. mid - 1 for an even earlier True. Case 2: bad[mid] is False [ False, False, False | False | ... ? ... ] left mid right -> Because bad is monotonic, everything up to mid MUST be False! Discard left .. mid and search ONLY mid + 1 .. right.Look how cleanly
first_bad = -1handles every boundary case without extraifchecks at the end: - Ifbadis empty ([]),left = 0andright = -1, soleft <= rightis immediatelyFalseand we return-1. - If every version isFalse, theif bad[mid]:branch never runs, sofirst_badstays-1. - WheneverTrueis found at an earlier and earliermid,first_badgets overwritten with that smaller index until no earlierTrueexists.Why the loop is guaranteed to finish in O(log n) steps
Binary search bugs almost always come from infinite loops when
leftandrightare 1 apart. Notice why our loop cannot loop forever:- In Case 1 (
bad[mid]isTrue), we setright = mid - 1. - In Case 2 (
bad[mid]isFalse), we setleft = mid + 1.
In both cases,
miditself is removed from[left, right]and at least half of the remaining window is thrown away! Starting from1,000,000versions, halving20times drops below1(2^20 = 1,048,576), so the loop finishes in at most20reads.def first_bad_version(bad: list[bool]) -> int: # Inclusive search window [left, right] of unchecked version indices. # When bad is empty, right starts at -1 and the while loop skips cleanly. left = 0 right = len(bad) - 1 # first_bad: earliest index seen so far where bad[index] is True, or -1 if none. first_bad = -1 while left <= right: mid = (left + right) // 2 if bad[mid]: # mid is bad: record it as our best candidate so far, then search # strictly left (left .. mid - 1) in case an earlier version broke first. first_bad = mid right = mid - 1 else: # mid is good: monotonicity guarantees every index <= mid is also good, # so the first bad version can only live strictly right (mid + 1 .. right). left = mid + 1 return first_bad- In Case 1 (
Trace all three examples step by step
Let's trace the pointers on every example input to see the exact updates:
Example 1: bad = [False, False, False, True, True, True, True] Start: left = 0, right = 6, first_bad = -1 Step 1: mid = (0 + 6) // 2 = 3 -> bad[3] is True -> first_bad = 3, right = 2 Step 2: mid = (0 + 2) // 2 = 1 -> bad[1] is False -> left = 2 Step 3: mid = (2 + 2) // 2 = 2 -> bad[2] is False -> left = 3 Stop (left=3 > right=2) -> return first_bad = 3 Example 2: bad = [False, False, False, False] Start: left = 0, right = 3, first_bad = -1 Step 1: mid = (0 + 3) // 2 = 1 -> bad[1] is False -> left = 2 Step 2: mid = (2 + 3) // 2 = 2 -> bad[2] is False -> left = 3 Step 3: mid = (3 + 3) // 2 = 3 -> bad[3] is False -> left = 4 Stop (left=4 > right=3) -> return first_bad = -1 Example 3: bad = [True, True, True] Start: left = 0, right = 2, first_bad = -1 Step 1: mid = (0 + 2) // 2 = 1 -> bad[1] is True -> first_bad = 1, right = 0 Step 2: mid = (0 + 0) // 2 = 0 -> bad[0] is True -> first_bad = 0, right = -1 Stop (left=0 > right=-1) -> return first_bad = 0Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def first_bad_version(bad: list[bool]) -> int: # Inclusive search window [left, right] of unchecked version indices. # When bad is empty, right starts at -1 and the while loop skips cleanly. left = 0 right = len(bad) - 1 # first_bad: earliest index seen so far where bad[index] is True, or -1 if none. first_bad = -1 while left <= right: mid = (left + right) // 2 if bad[mid]: # mid is bad: record it as our best candidate so far, then search # strictly left (left .. mid - 1) in case an earlier version broke first. first_bad = mid right = mid - 1 else: # mid is good: monotonicity guarantees every index <= mid is also good, # so the first bad version can only live strictly right (mid + 1 .. right). left = mid + 1 return first_bad✅ Submit now — all tests should pass.
Intuition & how it works
Think of tracking down which daily software build introduced a bug — the exact job performed by git bisect. Because the release history is a monotonic array (a sequence that moves in only one direction, here from False to True with no False ever appearing after a True), every version before the bug is good (False) and every version from the bug onward is broken (True). Instead of testing builds one by one from day 0, binary search (an algorithm that repeatedly tests the middle item to throw away half of the remaining candidates) jumps straight to the middle release: if it is broken, we remember its index and look earlier; if it is healthy, we throw away the entire first half and look later.
Scanning from left to right (for i in range(len(bad)) or bad.index(True)) ignores this clean split and reads up to 1,000,000 versions in the worst case — and bad.index(True) even crashes with a ValueError when every version is good! Slicing the list (bad[:mid]) during recursion is another subtle trap because copying half the array turns a fast search back into O(n) work. Moving two integer pointers left and right in place finds the exact boundary in at most 20 reads for a million versions.
Let's walk through Example 1 with 7 builds: bad = [False, False, False, True, True, True, True].
1. Start with left = 0, right = 6, and first_bad = -1.
2. Check middle mid = (0 + 6) // 2 = 3: bad[3] is True, so save first_bad = 3 and pull right = 2 to inspect earlier indices 0..2.
3. Check middle mid = (0 + 2) // 2 = 1: bad[1] is False, so indices 0..1 passed; advance left = 2.
4. Check middle mid = (2 + 2) // 2 = 2: bad[2] is False, so advance left = 3.
5. Now left = 3 > right = 2, so the loop finishes and returns first_bad = 3 after only 3 reads.
Complexity
- Time —
O(log n): Every iteration inspects one middle elementbad[mid]and discardsmidalong with either everything to its left or everything to its right, cutting the remaining window[left, right]at least in half. Forn >= 1, the window empties in at mostfloor(log2(n)) + 1iterations (at most20reads whenn = 1,000,000). - Space —
O(1): We only keep four integer variables (left,right,first_bad,mid) regardless of how largebadis, with zero array copies or recursion frames.
Edge cases
- Empty history (
bad = []):rightstarts atlen(bad) - 1 = -1, sowhile left <= right(0 <= -1) does zero iterations and returnsfirst_bad = -1. - All versions good (
[False, False, ...]): Every probe takes theelsebranch untilleftwalks pastlen(bad) - 1, returning-1. - All versions bad (
[True, True, ...]):first_badkeeps stepping leftward down to0, thenrightbecomes-1and the function returns0. - Only the very last version is bad (
[False, ..., False, True]):leftclimbs all the way tolen(bad) - 1, readsTrueon the final step, recordsfirst_bad = len(bad) - 1, and stops. - Single-element lists (
[True]and[False]): Tested atmid = 0in 1 iteration, returning0and-1respectively.
Common mistakes
- Mixing
while left <= rightwithright = mid: Ifleft == rightandbad[mid]isTrue, settingright = midleavesleftandrightunchanged and causes an infinite loop! Recordingfirst_bad = midlets us safely moveright = mid - 1every time. - Returning
leftwithout checking whether anyTrueexisted: In a half-open search withoutfirst_bad, an all-Falselist ends withleft == len(bad)(orlen(bad) - 1), returning an out-of-bounds or good index instead of-1. - Slicing the list (
bad[mid + 1:]): Slicing copiesO(n)booleans in Python, making total runtimeO(n + n/2 + n/4 + ...) = O(n)instead ofO(log n). - Calling
True in badorbad.index(True): Both scan element by element from index0inO(n)time, failing logarithmic read-count checks on large inputs. - Midpoint integer overflow in C++ or Java: In fixed-width 32-bit integer languages,
(left + right) / 2can overflow2^31 - 1whennexceeds a billion; writeleft + (right - left) / 2there (Pythoninthas arbitrary precision and cannot overflow).
Alternative approaches
- Half-open boundary binary search (
[lo, hi)): Maintain a loop invariant (a rule guaranteed to stay true before and after every iteration) where every index< loisFalseand every index>= hiisTrue, starting withlo = 0, hi = len(bad)and loopingwhile lo < hi:. Sethi = midwhenbad[mid]isTrueandlo = mid + 1otherwise; at the end, return-1iflo == len(bad)elselo. - Python's built-in
bisect.bisect_left: BecauseFalse == 0andTrue == 1in Python, a monotonic boolean list is already sorted in non-decreasing order! Callingidx = bisect.bisect_left(bad, True)finds the boundary inO(log n)time (return -1 if idx == len(bad) else idx), though in an interview you should write the binary-search loop yourself first.
Follow-up questions
- How does the approach adapt when versions 1..n are checked through an expensive API call, or across k parallel test runners? Run the exact same loop with
left = 1, right = n, callingis_bad(mid)once per iteration — noticemidis excluded from future ranges on every step, so no version is ever tested twice and memoization adds nothing. If you havekbuild runners that can test in parallel, probekevenly spaced versions per round to split the range intok + 1pieces, cutting the number of sequential rounds fromlog2(n)down tolog(n) / log(k + 1)(for example,k = 9runners pinpoint the broken build among1,000,000versions in6rounds instead of20). - How could you find the earliest broken build if the total count of builds is unknown ahead of time? Use exponential (galloping) search (probing indices
0, 1, 2, 4, 8, 16, ...by doubling each step untilis_bad(probe)returnsTrue). Onceprobeis broken (and the previous stepprevwas healthy), run standard binary search on[prev + 1, probe]; if the earliest broken build sits at indexB, both phases takeO(log B)probes total without ever needingn. - What changes if the test check is occasionally noisy, or if regressions can be patched and broken again later? If only the test runner is noisy while the underlying builds remain monotonic, re-run
is_bad(mid)an odd number of times (say 3 or 5) and take the majority vote at each binary-search step. If the history itself is non-monotonic (False, True, False, True), binary search can land on a later transition and miss an isolated earlyTruehidden in the skipped half — finding the guaranteed earliestTruein an arbitrary boolean array requiresO(n)reads in the worst case.
Follow-up questions
- How does the approach adapt when versions 1..n are checked through an expensive API call, or across k parallel test runners?
- How could you find the earliest broken build if the total count of builds is unknown ahead of time?
- What changes if the test check is occasionally noisy, or if regressions can be patched and broken again later?
Similar questions
- Diameter of an Unweighted Tree
- A* Grid Maze Pathfinding
- C++ Language Semantics and GPU Kernel Trade-offs
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses