Find the element before which all the elements are smaller than it, and after which all are greater in Python


Suppose we have an array, we have to find an element before which all elements are less than it, and after which all are greater than it. Finally, return the index of the element, if there is no such element, then return -1.

So, if the input is like A - [6, 2, 5, 4, 7, 9, 11, 8, 10], then the output will be 4.

To solve this, we will follow these steps −

  • n := size of arr

  • maximum_left := an array of size n

  • maximum_left[0] := -infinity

  • for i in range 1 to n, do

    • maximum_left[i] := maximum of maximum_left[i-1], arr[i-1]

  • minimum_right := infinity

  • for i in range n-1 to -1, decrease by 1, do

    • if maximum_left[i] < arr[i] and minimum_right > arr[i], then

      • return i

    • minimum_right := minimum of minimum_right, arr[i]

      • return -1

Example 

Let us see the following implementation to get better understanding −

 Live Demo

def get_element(arr):
   n = len(arr)
   maximum_left = [None] * n
   maximum_left[0] = float('-inf')
   for i in range(1, n):
      maximum_left[i] = max(maximum_left[i-1], arr[i-1])
   minimum_right = float('inf')
   for i in range(n-1, -1, -1):
      if maximum_left[i] < arr[i] and minimum_right > arr[i]:
         return i
      minimum_right = min(minimum_right, arr[i])
   return -1
arr = [6, 2, 5, 4, 7, 9, 11, 8, 10]
print(get_element(arr))

Input

[6, 2, 5, 4, 7, 9, 11, 8, 10]

Output

4

Updated on: 19-Aug-2020

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements