I have a list of integers and I am trying to achieve O(log n) by using a recursive algorithm to identify a dip in a list of integers. A dip is any number which is immediately followed by and follows a number equal than or greater than itself, and follows, such that x >= dip <= y. First and last elements can be considered dips as long as the number next to them is greater than or equal to these elements.
I have been able to achieve O(n) by simply iterating through the list, however I'm trying to use an approach similar to the binary search algorithm to achieve a faster result. I only need to find a single dip in the list.
My problem is when I separate the list into left and right of the midpoint I eventually reach smaller lists with one/two elements but they are not necessarily pits as they do not take into consideration the numbers just outside of their slices.
Can anyone help me?
def find_dip(lst):
if len(lst) == 1:
return 0
elif len(lst) == 2:
if lst[0] <= lst[1]:
return 0
else:
return 1
else:
ans = False
mid = len(lst) // 2
print("test")
if lst[mid-1] >= lst[mid] <= lst[mid+1]:
ans = mid
elif ans == False and len(lst[mid:]) > 2:
if lst[mid] >= lst[mid+1] <= lst[mid+2]:
ans = mid+1
elif ans == False and len(lst[:mid]) > 2:
if lst[mid-2] >= lst[mid-1] <= lst[mid]:
ans = mid-1
elif ans == False:
ans = find_dip(lst[:mid])
else:
ans = find_dip(lst[mid+1:])
return ans