educative.io

[Ask] is this implementation better?


#1

Is it really necessary to find the max value first then to do binary search to left and right?

what do you guys think about this implementation?

def find_target_given_bitonic_array(bitonic_array, target):
      left, right = 0, len(bitonic_array) - 1
      while left <= right:
           mid = left + (right - left) // 2
           if bitonic_array[mid] == target:
                 return mid
          if mid + 1 < len(bitonic_array) and bitonic_array[mid + 1] > bitonic_array[mid]: # mid in increasing side
               if bitonic_array[mid] > target:
                     right = mid - 1
               else:
                    left = mid + 1
          else:
               if bitonic_array[mid] > target:
                   left = mid + 1
               else:
                   right = mid - 1

       return -1

is this optimal? I am asking since I am pretty new on this ds and algorithm thing and would really know if I am on a right track since this is the first solution that came to my mind.

Thank you