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

Given an array, find an element before which all elements are smaller than it, and after which all are greater than it. Return the index of the element if there is such an element, otherwise, return -1.

Examples:

Input: arr[] = {5, 1, 4, 3, 6, 8, 10, 7, 9};
Output: 4
Explanation: All elements on left of arr are smaller than it
and all elements on right are greater.

Input: arr[] = {5, 1, 4, 4};
Output: -1
Explanation : No such index exits.

Expected time complexity: O(n).

## Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.

A simple solution is to consider every element one by one. For every element, compare it with all elements on the left and all elements on right. Time complexity of this solution is O(n2).

An Efficient Solution can solve this problem in O(n) time using O(n) extra space. Below is detailed solution.

1. Create two arrays leftMax[] and rightMin[].
2. Traverse input array from left to right and fill leftMax[] such that leftMax[i] contains maximum element from 0 to i-1 in input array.
3. Traverse input array from right to left and fill rightMin[] such that rightMin[i] contains minimum element from to n-1 to i+1 in input array.
4. Traverse input array. For every element arr[i], check if arr[i] is greater than leftMax[i] and smaller than rightMin[i]. If yes, return i.

A Further Optimization to the above approach is to use only one extra array and traverse input array only twice. The first traversal is the same as above and fills leftMax[]. Next traversal traverses from the right and keeps track of the minimum. The second traversal also finds the required element.

Below image is a dry run of the above approach: Below is the implementation of above approach.

## C/C++

 `// C++ program to find the element which is greater than ` `// all left elements and smaller than all right elements. ` `#include ` `using` `namespace` `std; ` ` `  `// Function to return the index of the element which is greater than ` `// all left elements and smaller than all right elements. ` `int` `findElement(``int` `arr[], ``int` `n) ` `{ ` `    ``// leftMax[i] stores maximum of arr[0..i-1] ` `    ``int` `leftMax[n]; ` `    ``leftMax = INT_MIN; ` ` `  `    ``// Fill leftMax[]1..n-1] ` `    ``for` `(``int` `i = 1; i < n; i++) ` `        ``leftMax[i] = max(leftMax[i-1], arr[i-1]); ` ` `  `    ``// Initialize minimum from right ` `    ``int` `rightMin = INT_MAX; ` ` `  `    ``// Traverse array from right ` `    ``for` `(``int` `i=n-1; i>=0; i--) ` `    ``{ ` `        ``// Check if we found a required element ` `        ``if` `(leftMax[i] < arr[i] && rightMin > arr[i]) ` `             ``return` `i; ` ` `  `        ``// Update right minimum ` `        ``rightMin = min(rightMin, arr[i]); ` `    ``} ` ` `  `    ``// If there was no element matching criteria ` `    ``return` `-1; ` `} ` ` `  `// Driver program ` `int` `main() ` `{ ` `    ``int` `arr[] = {5, 1, 4, 3, 6, 8, 10, 7, 9}; ` `    ``int` `n = ``sizeof` `arr / ``sizeof` `arr; ` `    ``cout << ``"Index of the element is "` `<< findElement(arr, n); ` `    ``return` `0; ` `} `

## Java

 `// Java program to find the element which is greater than ` `// all left elements and smaller than all right elements. ` `import` `java.io.*; ` `import` `java.util.*; ` ` `  `public` `class` `GFG { ` `       ``static` `int` `findElement(``int``[] arr, ``int` `n) ` `       ``{ ` `              ``// leftMax[i] stores maximum of arr[0..i-1]  ` `              ``int``[] leftMax = ``new` `int``[n]; ` `              ``leftMax[``0``] = Integer.MIN_VALUE; ` ` `  `              ``// Fill leftMax[]1..n-1]  ` `              ``for` `(``int` `i = ``1``; i < n; i++) ` `                   ``leftMax[i] = Math.max(leftMax[i - ``1``], arr[i - ``1``]); ` `                    `  `              ``// Initialize minimum from right  ` `              ``int` `rightMin = Integer.MAX_VALUE; ` ` `  `              ``// Traverse array from right  ` `              ``for` `(``int` `i = n - ``1``; i >= ``0``; i--)  ` `              ``{ ` `                   ``// Check if we found a required element ` `                   ``if` `(leftMax[i] < arr[i] && rightMin > arr[i]) ` `                       ``return` `i; ` ` `  `                   ``// Update right minimum ` `                   ``rightMin = Math.min(rightMin, arr[i]);  ` `              ``} ` `                `  `              ``// If there was no element matching criteria  ` `              ``return` `-``1``; ` ` `  `               `  `       ``} ` ` `  `       ``// Driver code ` `       ``public` `static` `void` `main(String args[]) ` `       ``{ ` `              ``int``[] arr = {``5``, ``1``, ``4``, ``3``, ``6``, ``8``, ``10``, ``7``, ``9``}; ` `              ``int` `n = arr.length; ` `              ``System.out.println(``"Index of the element is "` `+  ` `              ``findElement(arr, n)); ` `       ``} ` ` `  `       ``// This code is contributed ` `       ``// by rachana soma ` `} `

## Python3

 `# Python3 program to find the element which is greater than  ` `# all left elements and smaller than all right elements.  ` ` `  `def` `findElement(arr, n):  ` `  `  `    ``# leftMax[i] stores maximum of arr[0..i-1]  ` `    ``leftMax ``=` `[``None``] ``*` `n  ` `    ``leftMax[``0``] ``=` `float``(``'-inf'``)  ` ` `  `    ``# Fill leftMax[]1..n-1]  ` `    ``for` `i ``in` `range``(``1``, n):  ` `        ``leftMax[i] ``=` `max``(leftMax[i``-``1``], arr[i``-``1``])  ` ` `  `    ``# Initialize minimum from right  ` `    ``rightMin ``=` `float``(``'inf'``)  ` ` `  `    ``# Traverse array from right  ` `    ``for` `i ``in` `range``(n``-``1``, ``-``1``, ``-``1``):  ` `      `  `        ``# Check if we found a required element  ` `        ``if` `leftMax[i] < arr[i] ``and` `rightMin > arr[i]:  ` `            ``return` `i  ` ` `  `        ``# Update right minimum  ` `        ``rightMin ``=` `min``(rightMin, arr[i])  ` `      `  `    ``# If there was no element matching criteria  ` `    ``return` `-``1`  ` `  `# Driver program  ` `if` `__name__ ``=``=` `"__main__"``:  ` ` `  `    ``arr ``=` `[``5``, ``1``, ``4``, ``3``, ``6``, ``8``, ``10``, ``7``, ``9``]  ` `    ``n ``=` `len``(arr)  ` `    ``print``(``"Index of the element is"``, findElement(arr, n)) ` `  `  `# This code is contributed by Rituraj Jain `

## C#

 `// C# program to find the element which is greater than ` `// all left elements and smaller than all right elements. ` `using` `System; ` ` `  `class` `GFG ` `{ ` `static` `int` `findElement(``int``[] arr, ``int` `n) ` `{ ` `    ``// leftMax[i] stores maximum of arr[0..i-1] ` `    ``int``[] leftMax = ``new` `int``[n]; ` `    ``leftMax = ``int``.MinValue; ` ` `  `    ``// Fill leftMax[]1..n-1] ` `    ``for` `(``int` `i = 1; i < n; i++) ` `        ``leftMax[i] = Math.Max(leftMax[i - 1], arr[i - 1]); ` ` `  `    ``// Initialize minimum from right ` `    ``int` `rightMin = ``int``.MaxValue; ` ` `  `    ``// Traverse array from right ` `    ``for` `(``int` `i=n-1; i>=0; i--) ` `    ``{ ` `        ``// Check if we found a required element ` `        ``if` `(leftMax[i] < arr[i] && rightMin > arr[i]) ` `            ``return` `i; ` ` `  `        ``// Update right minimum ` `        ``rightMin = Math.Min(rightMin, arr[i]); ` `    ``} ` ` `  `    ``// If there was no element matching criteria ` `    ``return` `-1; ` `} ` ` `  `// Driver program ` `public` `static` `void` `Main() ` `{ ` `    ``int``[] arr = {5, 1, 4, 3, 6, 8, 10, 7, 9}; ` `    ``int` `n = arr.Length; ` `    ``Console.Write( ``"Index of the element is "` `+ findElement(arr, n)); ` `} ` `} ` ` `  `// This code is contributed  ` `// by Akanksha Rai(Abby_akku) `

## PHP

 `= 0; ``\$i``--)  ` `    ``{  ` `        ``// Check if we found a required ` `        ``// element  ` `        ``if` `(``\$leftMax``[``\$i``] < ``\$arr``[``\$i``] &&  ` `            ``\$rightMin` `> ``\$arr``[``\$i``])  ` `            ``return` `\$i``;  ` ` `  `        ``// Update right minimum  ` `        ``\$rightMin` `= min(``\$rightMin``, ``\$arr``[``\$i``]);  ` `    ``}  ` ` `  `    ``// If there was no element ` `    ``// matching criteria  ` `    ``return` `-1;  ` `}  ` ` `  `// Driver Code  ` `\$arr` `= ``array``(5, 1, 4, 3, 6, 8, 10, 7, 9);  ` `\$n` `= ``count``(``\$arr``); ` `echo` `"Index of the element is "` `,  ` `           ``findElement(``\$arr``, ``\$n``);  ` ` `  `// This code is contributed ` `// by Sach_Code ` `?> `

Output:

`Index of the element is 4`

Time Complexity: O(n)
Auxiliary Space: O(n)

Thanks to Gaurav Ahirwar for suggesting above solution.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Article Tags :

20

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.