Working on below find first bad version problem, post my code in Python 2.7, any smarter ideas for better time complexity, any code bug or code style advice are highly appreciated. My major idea is divide and conquer like a binary search.
Problem,
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.
Source code,
def isBadVersion(number):
if number == 0:
return False
else:
return True
# 0 means good, 1 means bad
def find_first_bad_index(numbers):
start = 0
end = len(numbers)-1
if isBadVersion(numbers[start]) == True:
return start
if isBadVersion(numbers[end]) == False:
raise Exception('all good')
while start <= end:
mid = start + (end-start)/2
if isBadVersion(numbers[mid]) == True:
if start == end:
return end
else:
end = mid
else:
start = mid + 1
if __name__ == "__main__":
print find_first_bad_index([0,0,0,1,1,1,1,1])
print find_first_bad_index([0,0,0,0,0,0,0,1])