Algorithms · Binary search
First Bad Version
A bug crept in at some version. Find the first broken one.
The problem
Your app has versions 0, 1, 2…. At some point a bug crept in, and every version after it is broken too. versions[i] is True if version i is broken. Return the first broken version. (LeetCode gives you a function to call instead of a list.)
first_bad([False, False, True, True])→2first_bad([True])→0Start with the way that works
This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.
def first_bad(versions):take broken (True) / fine (False) for each version for i in range(len(versions)):check each version, oldest first if versions[i]:broken? return ithe first broken oneNow ask: what if there were a billion?
This is exactly git bisect: among 10,000 commits it finds the one that broke your app in about 14 tests. Linux kernel developers use it to hunt bugs across years of history.
Aim for O(log n)🧩 classic
Think it through
Version 50 is broken. Where is the first bad one?
- After 50
- At 50 or before it
Show the answer
At 50 or before it. Once broken, always broken after. So a broken middle means the first bad one is there or earlier. A working middle means later.
Each check takes ten minutes (build and test). Why does that make halving matter so much?
- It doesn’t
- It turns hundreds of checks into about ten
Show the answer
It turns hundreds of checks into about ten. When a check is expensive, the number of checks is everything. This is exactly git bisect: find the commit that broke things in a handful of builds.
Stuck? 3 nudges, smallest first
- Checking a version can be slow in real life (you have to build and test it). How few checks can you get away with?
- Test the middle version. If it’s broken, the first bad one is there or earlier. If it’s fine, it’s later.
- Keep
lo, hi. Whilelo < hi: ifversions[mid]is broken,hi = mid, elselo = mid + 1. Returnlo.
The fast way
Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.
Show the fast version
def first_bad(versions):take broken (True) / fine (False) for each version lo, hi = 0, len(versions) - 1the first bad one is somewhere in here while lo < hi:until only one version is left mid = (lo + hi) // 2test the middle version if versions[mid]:broken? hi = midthe first bad one is here or earlier else:fine lo = mid + 1the first bad one is later return lothe only version leftWhere it’s used for real
Solve it yourself.
It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.