First Bad Version - String - Easy - LeetCode
💻 coding

First Bad Version - String - Easy - LeetCode

1 min read 202 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to identify the first bad version of a product among n versions using a given API.
  • 2The solution involves a binary search algorithm to minimize API calls, achieving O(log n) time complexity.
  • 3The implementation uses a while loop to narrow down the search range until the first bad version is found.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to identify the first bad version of a product among n versions using a given API."

First Bad Version - String - Easy - LeetCode

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 will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true

Then 4 is the first bad version.

/* The isBadVersion API is defined in the parent class VersionControl.
 bool IsBadVersion(int version); */

public class Solution : VersionControl {
 public int FirstBadVersion(int n) {
 int start = 1;
 int end = n;
 while(start<end){
 int mid = start + (end-start)/2;
 if(IsBadVersion(mid)){
 end = mid;
 }
 else{
 start = mid+1;
 }
 }
 return start;
 }
}

Time Complexity: O(logn)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 3 October 2020 · 1 min read · 202 words

Part of AskGif Blog · coding

You might also like