First Bad Version — LeetCode 278 Python Solution
- Problem
- #278
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
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
# 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 lComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log n) |
| Space | O(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.