#278

First Bad Version

Easy First true

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Versions 1..n are good up to some point and bad after it. Using an isBadVersion(v) API, find the first bad version with as few calls as possible.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: versions go good, good, …, bad, bad. Find the first bad.

Why this works: if mid is bad, the answer is mid or before; if good, it's after.

Example: n = 5, first bad = 4

mid 3 good → lo 4mid 4 bad → hi 4 → answer 4

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

(lo + hi) / 2 overflows when n is close to 2^31.

Solve on LeetCode ↗
Complexity
  • Time: O(log n).
  • Space: O(1).
Topic: Binary Search
🎬 Episodes 21–23: video coming soon