Leetcode 278: First Bad Version

grid47
grid47
Exploring patterns and algorithms
Oct 10, 2024 5 min read

A series of versions, with the first bad one glowing brightly, indicating where the bad version starts.
Solution to LeetCode 278: First Bad Version Problem

You are managing a product development process where each version of the product is based on its previous version. However, you have a version that failed the quality check. Since all subsequent versions are based on the previous ones, they also fail the quality check. Your task is to find the first bad version that caused all subsequent versions to be bad. You are given an API bool isBadVersion(version) that returns true if the version is bad, and false otherwise. Your goal is to find the first bad version while minimizing the number of calls to the API.
Problem
Approach
Steps
Complexity
Input: You are given an integer `n`, representing the total number of versions, and a function `isBadVersion(version)` that tells whether a version is bad or not.
Example: Input: n = 6, bad = 4
Constraints:
• 1 <= bad <= n <= 2^31 - 1
Output: Return the first bad version number that causes all subsequent versions to be bad.
Example: Output: 4
Constraints:
• The output should be the version number of the first bad version.
Goal: Find the first bad version by minimizing the number of calls to `isBadVersion`.
Steps:
• Step 1: Use binary search to find the first bad version.
• Step 2: Initialize two pointers: start at 1 and end at n.
• Step 3: Compute the midpoint of the current range.
• Step 4: If the midpoint is a bad version, narrow the search range to the left half (end = mid). Otherwise, narrow the search range to the right half (start = mid + 1).
• Step 5: Repeat this process until the start pointer equals the end pointer, which will indicate the first bad version.
Goal: The problem involves finding a specific version that causes all subsequent versions to be bad, with a focus on optimizing the number of API calls.
Steps:
• The string length is between 1 and 1000.
• The string contains only lowercase English letters.
Assumptions:
• The `isBadVersion` function is available and can be called.
• You need to minimize the number of calls to the `isBadVersion` API.
Input: Input: n = 6, bad = 4
Explanation: The versions are [1, 2, 3, 4, 5, 6]. The first bad version is 4. The binary search process calls `isBadVersion(3)` (false), then `isBadVersion(5)` (true), and finally `isBadVersion(4)` (true), thus returning 4.

Input: Input: n = 1, bad = 1
Explanation: Since there is only one version and it is bad, the function immediately returns 1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus