First Bad Version — LeetCode 278 Python Solution

EasyBinary SearchInteractive
Problem
#278
Reading time
3 min

The 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.

Example

Input
n = 5, bad = 4
Output
4
Explanation
call isBadVersion(3) -> false

Python solution

Python
# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:


class Solution:
    def firstBadVersion(self, n: int) -> int:
        l, r = 1, n
        while l < r:
            mid = (l + r) >> 1
            if isBadVersion(mid):
                r = mid
            else:
                l = mid + 1
        return l

Complexity

MeasureComplexity
TimeO(\log n)
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 278. First Bad Version is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

On a study list

This problem is on Grind 75.

Frequently asked questions

How hard is LeetCode 278. First Bad Version?
LeetCode 278. First Bad Version is rated Easy on LeetCode.
What is the time complexity of LeetCode 278. First Bad Version?
The Python solution on this page runs in O(\log n).
What is the space complexity of LeetCode 278. First Bad Version?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 278. First Bad Version cover?
LeetCode 278. First Bad Version is tagged Binary Search and Interactive on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview