Skip to main content

18. First Bad Version

easyAsked at Etsy

Binary-search for the first failing deployment version — Etsy's CI pipeline problem that every engineer needs to solve before touching their release train.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. You have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Constraints

  • 1 <= bad <= n <= 2^31 - 1
  • isBadVersion is provided — do not implement it
  • Minimize API calls

Examples

Example 1

Input
n = 5, bad = 4
Output
4 (versions 1,2,3 are good; 4,5 are bad)

Example 2

Input
n = 1, bad = 1
Output
1

Approaches

1. Linear scan

Call isBadVersion on every version from 1 to n until the first true result. O(n) API calls — too slow for large n.

Time
O(n)
Space
O(1)
function solution(isBadVersion) {
  return function(n) {
    for (let v = 1; v <= n; v++) {
      if (isBadVersion(v)) return v;
    }
  };
}

Tradeoff:

2. Binary search

Maintain lo and hi. If mid is bad, the first bad version is at mid or before — move hi to mid. Otherwise move lo past mid. Loop until lo === hi.

Time
O(log n)
Space
O(1)
function solution(isBadVersion) {
  return function(n) {
    let lo = 1, hi = n;
    while (lo < hi) {
      const mid = lo + Math.floor((hi - lo) / 2);
      if (isBadVersion(mid)) {
        hi = mid;
      } else {
        lo = mid + 1;
      }
    }
    return lo;
  };
}

Tradeoff:

Etsy-specific tips

Etsy interviewers watch for integer overflow — using `lo + Math.floor((hi - lo) / 2)` instead of `(lo + hi) / 2` signals you know the production gotcha. Be ready to extend this to a 2D grid of versions (find first bad row) if the interviewer escalates.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill First Bad Version and other Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →