#278

First Bad Version

Easy
Binary SearchInteractiveBinary SearchInteractive Problems
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(log n)
Space
O(1)
O(1)
💡

Intuition

Time O(log n)Space O(1)

Using binary search allows us to efficiently narrow down the search space for the first bad version. This is much faster than checking each version sequentially.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize two pointers, left = 1 and right = n.
  2. 2Step 2: While left < right, calculate mid = left + (right - left) // 2.
  3. 3Step 3: If isBadVersion(mid) is true, set right = mid (search left side). Otherwise, set left = mid + 1 (search right side).
  4. 4Step 4: When left equals right, return left as the first bad version.
solution.py11 lines
1# Full working Python code
2class Solution:
3    def firstBadVersion(self, n: int) -> int:
4        left, right = 1, n
5        while left < right:
6            mid = left + (right - left) // 2
7            if isBadVersion(mid):
8                right = mid
9            else:
10                left = mid + 1
11        return left

Complexity note: The time complexity is O(log n) due to the binary search approach, which halves the search space with each iteration. The space complexity remains O(1) as we are using a constant amount of space.

  • 1Using binary search significantly reduces the number of API calls.
  • 2Understanding the relationship between versions helps in efficiently narrowing down the search.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.