- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

Let us see the following implementation to get better understanding −

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))

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

4

- Related Questions & Answers
- Program to filter all values which are greater than x in an array
- Find the Number of segments where all elements are greater than X using C++
- Find all elements in array which have at-least two greater elements in C++
- Python Program to Find all Numbers in a Range which are Perfect Squares and Sum of all Digits in the Number is Less than 10
- Program to find number of elements in all permutation which are following given conditions in Python
- Delete all the nodes from the list that are greater than x in C++
- How to find all records which are NOT in the set array with MySQL?
- Program to find list of elements which are less than limit and XOR is maximum in Python
- Find an array element such that all elements are divisible by it using c++
- Program to find sum of two numbers which are less than the target in Python
- Program to find number not greater than n where all digits are non-decreasing in python
- Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers
- Which grapes are the tastiest?
- What does immutable mean? Which Python types are mutable and which are not?
- Rearrange array such that even index elements are smaller and odd index elements are greater in C++

Advertisements