This is not O(log n). In the worst case, there is no true element indexed thus this would continue to run in the amount of the size of the entire array. Making this in the worse case O(n)
can use too
def find_boundary(arr: List[bool]) → int:
# WRITE YOUR BRILLIANT CODE HERE
if len(arr) == 1 and arr[0]: return 0
if len(arr) == 1 and arr[0]: return -1
low, high = 0, len(arr) - 1
while low <= high:
mid = low + (high - low) // 2
if (arr[mid] and mid == 0) or (arr[mid] and not arr[mid - 1]):
return mid
if arr[mid] == False:
low = mid + 1
else:
high = mid - 1
return -1
def find_boundary(arr: List[bool]) → int:
# WRITE YOUR BRILLIANT CODE HERE
left, right = 0, len(arr)-1
while left < right:
mid = (left + right) //2
if arr[mid]:
right = mid
else:
left = mid + 1
if arr[left]:
return left
return -1
if name == ‘main’:
arr = [x == “true” for x in input().split()]
res = find_boundary(arr)
print(res)
public static int findBoundary(List<Boolean> arr) {
// WRITE YOUR BRILLIANT CODE HERE
int start=0;
int end=arr.size()-1;
while (start<=end)
{
int midle=end + (start-end) /2;
if(arr.get(midle))
{
// we found the first true
if(midle>0 && !arr.get(midle-1))
{
return midle;
}else if(midle>0 && arr.get(midle))
{
// we found a possible true then move on
// reduce the half
end=midle-1;
}else if(midle==0)
{ //corner case
return 0;
}
}else{
// if is it false then move on
start=midle+1;
}
}
return -1;
}
I believe when someone says time complexity is O(log n) for binary search, they are referring to amortized time (or average time). On interviews worst and best case can also be asked but usually people refer to amortized time
Could someone please explain for me, why we suppose that the first boundary_index going to be a first True value in an array to the left’s False? it can be the last one, isn’t it?
This problem is a major 🔑 in solving future binary search-related problems. As we will see in the following modules, many problems boil down to finding the boundary in a boolean array.