---
# System prepended metadata

title: '[278. First Bad Version](https://leetcode.com/problems/first-bad-version/)'
tags: [leetcode]

---

---
tags: leetcode
---

# [278. First Bad Version](https://leetcode.com/problems/first-bad-version/)
---
# My Solution
## The Key Idea for Solving This Coding Question
## C++ Code
```cpp=
// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int left = 1, right = n;
        while (left < right) {
            int middle = left + (right - left) / 2;
            if (isBadVersion(middle)) {
                right = middle;
            } else {
                left = middle + 1;
            }
        }

        if (isBadVersion(left)) {
            return left;
        }
        return left + 1;
    }
};
```
## Time Complexity
$O(logn)$
$n$ is the latest released version.
## Space Complexity
$O(1)$
# Miscellaneous
<!--
# Test Cases
```
5
4
```
```
1
1
```
* TLE:
```
1705930310
1508243771
```
-->