algoadvance

Leetcode 278. First Bad Version

Problem Statement:

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 boolean isBadVersion(int 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.

Clarifying Questions:

  1. What is the range of n (the number of versions)?
    • The range can be very large, typically in the order of millions.
  2. Does the function isBadVersion(int version) take a constant time to execute?
    • Yes, assume that the function takes constant time.
  3. Can we assume that there is at least one bad version in the list of versions?
    • Yes, you can assume that there is at least one bad version.

Strategy:

To minimize the number of calls to isBadVersion, a binary search strategy is appropriate. Binary search will reduce the number of calls to the function from O(n) to O(log n).

  1. Initialize two pointers left and right to 1 and n respectively.
  2. While the left pointer is less than the right pointer:
    • Calculate the middle version mid = left + (right - left) / 2.
    • Use the isBadVersion(mid) to check if mid is a bad version.
      • If mid is a bad version, then the first bad version must be at mid or before it, so adjust the right pointer to mid.
      • If mid is not a bad version, then the first bad version must be after mid, so adjust the left pointer to mid + 1.
  3. At the end of the loop, the left pointer should point to the first bad version.

Code:

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left = 1;
        int right = n;

        while (left < right) {
            int mid = left + (right - left) / 2;

            if (isBadVersion(mid)) {
                right = mid; // Look on the left side including mid
            } else {
                left = mid + 1; // Look on the right side excluding mid
            }
        }
        return left;
    }
}

Time Complexity:

This solution efficiently finds the first bad version by reducing the problem size in half with each iteration.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI