0278. First Bad Version

278. First Bad Version #

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.

Suppose 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 bool 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.

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Constraints:

  • 1 <= bad <= n <= 231 - 1

Problem Summary #

You are a product manager, currently leading a team to develop a new product. Unfortunately, the latest version of your product did not pass the quality check. Since each version is developed based on the previous version, all versions after a bad version are also bad. Suppose you have n versions [1, 2, …, n], and you want to find the first bad version that causes all subsequent versions to be bad. You can determine whether the version number version fails the unit test by calling the bool isBadVersion(version) API. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Solution Approach #

  • We know that for iterative product versions, if a version is good, then all versions before it are good; if a version is bad, then all versions after it are bad. Using this property, we can perform binary search. Using binary search can also satisfy the requirement to reduce the number of API calls. Time complexity: O(logn), where n is the given number of versions. Space complexity: O(1).

Code #

package leetcode

import "sort"

/**
 * Forward declaration of isBadVersion API.
 * @param   version   your guess about first bad version
 * @return 	 	      true if current version is bad
 *			          false if current version is good
 * func isBadVersion(version int) bool;
 */

func firstBadVersion(n int) int {
	return sort.Search(n, func(version int) bool { return isBadVersion(version) })
}

Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文