![]() |
VOOZH | about |
Given an array arr[], find an element before which all elements are equal or smaller than it, and after which all the elements are equal or greater.
Note: Print -1, if no such element exists.
Examples:
Input: arr[] = [5, 1, 4, 3, 6, 8, 10, 7, 9]
Output: 6
Explanation: 6 is present at index 4. All elements on the left of arr[4] are smaller than it and all elements on right are greater.Input: arr[] = [5, 1, 4, 4]
Output: -1
Explanation: No such element exists.
Table of Content
The idea is to consider every non-boundary element of the given array arr[] one by one. For each element, find the largest element in left of it, and the smallest element in the right of it using the nested loops. If the largest element in its left is smaller or equal and the smallest element in its right is greater or equal, print the current element, else move to next. At last if no such element is found, print -1.
6
The idea is to precompute the largest values from index 0 to n - 1 and smallest values from n - 1 to 0. To do so,
6
The idea is to create a single array leftMax[] to store the largest elements at left of each index. And for right minimum values, we can use an integer rightMin that will store the current minimum value. At each iteration update the value rightMin and compare it with current value arr[i].
Below image is a dry run of the above approach:
6