Tutorialspoint
Problem
Solution
Submissions

First Bad Version

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to find the first bad version of a product. 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. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API bool isBadVersion(version) which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example 1
  • Input: n = 5, bad = 4
  • Output: 4
  • Explanation:
    We have versions [1, 2, 3, 4, 5] with version 4 as the first bad version.
    isBadVersion(3) -> false, isBadVersion(4) -> true, therefore version 4 is the first bad version.
Example 2
  • Input: n = 1, bad = 1
  • Output: 1
  • Explanation:
    We have only one version, which is version 1.
    isBadVersion(1) -> true, therefore version 1 is the first bad version.
Constraints
  • 1 ≤ bad ≤ n ≤ 2^31 - 1
  • You should call the isBadVersion API as few times as possible
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
AlgorithmsCognizantDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Consider using binary search to minimize the number of API calls
  • Initialize your search range from 1 to n
  • For each mid value, check if it's a bad version using the isBadVersion API
  • If mid is a bad version, search in the left half (including mid)
  • If mid is not a bad version, search in the right half (excluding mid)
  • Continue until the search range is narrowed down to a single version

Steps to solve by this approach:

 Step 1: Initialize two pointers, left = 1 and right = n.
 Step 2: While left is less than right, find the middle point mid = left + (right - left) / 2.
 Step 3: Check if mid version is bad using isBadVersion(mid).
 Step 4: If mid is a bad version, all versions after mid are also bad, so set right = mid.
 Step 5: If mid is not a bad version, all versions before and including mid are good, so set left = mid + 1.
 Step 6: Repeat steps 2-5 until left equals right.
 Step 7: Return left as the first bad version.

Submitted Code :