↓Skip to main content
  1. LeetCode/

LeetCode 278: First Bad Version

·1 min· ·
LeetCode Easy Binary-Search Interactive
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted ×3

Approach
#

Once broken, every later version is broken, so isBadVersion turns True at some point and stays; find the first (Binary Search Template 1): if mid is bad, r = mid, otherwise l = mid + 1.

My Solution
#

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

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • The bad mid may be the first; use r = mid, not mid - 1.

Interview Explanation
#

Every version after the first bad one is bad, so a lower-bound search shrinks the right bound to a bad middle and moves the left bound past a good one. Time O(log n).

Related

LeetCode 374: Guess Number Higher or Lower
·1 min
LeetCode Easy Binary-Search Interactive
LeetCode 374 note: adjust the range by guess’s result, where -1 means the guess is too high and 1 too low
LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 69: Sqrt(x)
·1 min
LeetCode Easy Math Binary-Search Newtons-Method
LeetCode 69 note: find the largest mid with mid² <= x; when a closed-interval search ends, r is the answer