- Related Questions & Answers
- 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
- 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 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?
- Checking if all array values are smaller than a limit using JavaScript
- How will you find out all the indexes which are built in a particular DB2 table?
- Return a subarray that contains all the element from the original array that are larger than all the elements on their right in JavaScript
- Finding the element larger than all elements on right - JavaScript
- Count all the columns in a matrix which are sorted in descending in C++

- 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

Advertisements