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] == True implies bad[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

  1. Understand the goal and what "monotonic" means

    We are given a boolean list bad representing a software release history from version 0 up to len(bad) - 1:

    • False means the release is good (passes tests).
    • True means the release is bad (contains the bug).

    The key rule in the problem statement is that bad is monotonic (one-directional: once a True appears, every later entry stays True, so False never appears after True):

    index:    0       1       2       3      4      5      6
    bad:   [False,  False,  False,  True,  True,  True,  True]
            \_______good________/   \______bad forever______/
                                    ^
                            earliest faulty build = index 3
    

    We want to return the smallest index where bad[i] is True, or -1 if no version is bad (including when bad is completely empty []). Because len(bad) can be up to 1,000,000, our code should inspect only a handful of entries rather than scanning the entire list.

  2. Start with a linear scan and see why we can do much better

    The simplest correct solution walks from index 0 to the end and returns the first True it sees:

    def first_bad_linear(bad: list[bool]) -> int:
        for i in range(len(bad)):
            if bad[i]:
                return i
        return -1
    

    Why isn't this enough in an interview (or in real engineering tools like git bisect)? Because if all 1,000,000 versions are good — or only the last version 999,999 is bad — a linear scan reads all one million entries. If checking each version meant compiling and testing a real software build, 1,000,000 checks could take weeks, whereas exploiting the False ... False, True ... True boundary takes at most 20 checks!

  3. 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 with left = 0 and right = len(bad) - 1, plus a variable first_bad = -1 holding 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 = -1 handles every boundary case without extra if checks at the end: - If bad is empty ([]), left = 0 and right = -1, so left <= right is immediately False and we return -1. - If every version is False, the if bad[mid]: branch never runs, so first_bad stays -1. - Whenever True is found at an earlier and earlier mid, first_bad gets overwritten with that smaller index until no earlier True exists.

  4. Why the loop is guaranteed to finish in O(log n) steps

    Binary search bugs almost always come from infinite loops when left and right are 1 apart. Notice why our loop cannot loop forever:

    • In Case 1 (bad[mid] is True), we set right = mid - 1.
    • In Case 2 (bad[mid] is False), we set left = mid + 1.

    In both cases, mid itself is removed from [left, right] and at least half of the remaining window is thrown away! Starting from 1,000,000 versions, halving 20 times drops below 1 (2^20 = 1,048,576), so the loop finishes in at most 20 reads.

    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
    
  5. 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 = 0
    
  6. Complete 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 element bad[mid] and discards mid along with either everything to its left or everything to its right, cutting the remaining window [left, right] at least in half. For n >= 1, the window empties in at most floor(log2(n)) + 1 iterations (at most 20 reads when n = 1,000,000).
  • Space — O(1): We only keep four integer variables (left, right, first_bad, mid) regardless of how large bad is, with zero array copies or recursion frames.

Edge cases

  • Empty history (bad = []): right starts at len(bad) - 1 = -1, so while left <= right (0 <= -1) does zero iterations and returns first_bad = -1.
  • All versions good ([False, False, ...]): Every probe takes the else branch until left walks past len(bad) - 1, returning -1.
  • All versions bad ([True, True, ...]): first_bad keeps stepping leftward down to 0, then right becomes -1 and the function returns 0.
  • Only the very last version is bad ([False, ..., False, True]): left climbs all the way to len(bad) - 1, reads True on the final step, records first_bad = len(bad) - 1, and stops.
  • Single-element lists ([True] and [False]): Tested at mid = 0 in 1 iteration, returning 0 and -1 respectively.

Common mistakes

  • Mixing while left <= right with right = mid: If left == right and bad[mid] is True, setting right = mid leaves left and right unchanged and causes an infinite loop! Recording first_bad = mid lets us safely move right = mid - 1 every time.
  • Returning left without checking whether any True existed: In a half-open search without first_bad, an all-False list ends with left == len(bad) (or len(bad) - 1), returning an out-of-bounds or good index instead of -1.
  • Slicing the list (bad[mid + 1:]): Slicing copies O(n) booleans in Python, making total runtime O(n + n/2 + n/4 + ...) = O(n) instead of O(log n).
  • Calling True in bad or bad.index(True): Both scan element by element from index 0 in O(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) / 2 can overflow 2^31 - 1 when n exceeds a billion; write left + (right - left) / 2 there (Python int has 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 < lo is False and every index >= hi is True, starting with lo = 0, hi = len(bad) and looping while lo < hi:. Set hi = mid when bad[mid] is True and lo = mid + 1 otherwise; at the end, return -1 if lo == len(bad) else lo.
  • Python's built-in bisect.bisect_left: Because False == 0 and True == 1 in Python, a monotonic boolean list is already sorted in non-decreasing order! Calling idx = bisect.bisect_left(bad, True) finds the boundary in O(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, calling is_bad(mid) once per iteration — notice mid is excluded from future ranges on every step, so no version is ever tested twice and memoization adds nothing. If you have k build runners that can test in parallel, probe k evenly spaced versions per round to split the range into k + 1 pieces, cutting the number of sequential rounds from log2(n) down to log(n) / log(k + 1) (for example, k = 9 runners pinpoint the broken build among 1,000,000 versions in 6 rounds instead of 20).
  • 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 until is_bad(probe) returns True). Once probe is broken (and the previous step prev was healthy), run standard binary search on [prev + 1, probe]; if the earliest broken build sits at index B, both phases take O(log B) probes total without ever needing n.
  • 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 early True hidden in the skipped half — finding the guaranteed earliest True in an arbitrary boolean array requires O(n) reads in the worst case.

Follow-up questions

Similar questions

More Qualcomm interview questions

All 4 Qualcomm questions →