First Bad Version in Python

PythonServer Side ProgrammingProgramming

Suppose in a company, one product manager is leading a team who develops a new product. Suppose latest version fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version will be bad. So we have an array A with n elements [1, 2, … n] and we have to find the first bad version from this array.

Consider we have a function isBadVersion(version_id), this will return whether the version is bad or not. For an example, suppose n = 5, and version = 4 is first bad version. So if the isBadVersion(3) returns false isBadVersion(5) returns true, and isBadVersion(4) also returns true, then the first bad version is 4

To solve this, we will follow these steps −

  • When n < 2, then return n
  • Perform binary search approach to detect bad version using the given function.

Example

Let us see the following implementation to get better understanding −

 Live Demo

first_bad = 0
def isBadVersion(version):
   if version >= first_bad:
      return True
   return False
class Solution:
   def firstBadVersion(self, n):
      if n <2:
         return n
      start = 1
      end = n
      while(start<=end):
         mid = (start+end)//2
         if isBadVersion(mid) and not isBadVersion(mid-1):
            return mid
         elif isBadVersion(mid-1):
            end = mid-1
         else:
            start = mid+1
ob1 = Solution()
first_bad = 4
op = ob1.firstBadVersion(5)
print(op)

Input

5
4

Output

4
raja
Published on 16-Jan-2020 15:02:33
Advertisements