Find the element before which all the elements are smaller than it, and after which all are greater
Last Updated :
25 Apr, 2023
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[4] 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).
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. The time complexity of this solution is O(n2).
Code-
C++
#include <bits/stdc++.h>
using namespace std;
bool check( int arr[], int n, int ind){
int i=ind-1;
int j=ind+1;
while (i>=0){
if (arr[i]>arr[ind]){ return false ;}
i--;
}
while (j<n){
if (arr[j]<arr[ind]){ return false ;}
j++;
}
return true ;
}
int findElement( int arr[], int n)
{
for ( int i=1; i<n-1; i++)
{
if (check(arr,n,i)){ return i;}
}
return -1;
}
int main()
{
int arr[] = {5, 1, 4, 3, 6, 8, 10, 7, 9};
int n = sizeof arr / sizeof arr[0];
cout << "Index of the element is " << findElement(arr, n);
return 0;
}
|
Java
import java.util.*;
class Main {
static boolean check( int arr[], int n, int ind)
{
int i = ind - 1 ;
int j = ind + 1 ;
while (i >= 0 ) {
if (arr[i] > arr[ind]) {
return false ;
}
i--;
}
while (j < n) {
if (arr[j] < arr[ind]) {
return false ;
}
j++;
}
return true ;
}
static int findElement( int arr[], int n)
{
for ( int i = 1 ; i < n - 1 ; i++) {
if (check(arr, n, i)) {
return i;
}
}
return - 1 ;
}
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));
}
}
|
Python3
def check(arr, n, ind):
i = ind - 1
j = ind + 1
while i > = 0 :
if arr[i] > arr[ind]:
return False
i - = 1
while j < n:
if arr[j] < arr[ind]:
return False
j + = 1
return True
def findElement(arr, n):
for i in range ( 1 , n - 1 ):
if check(arr, n, i):
return i
return - 1
arr = [ 5 , 1 , 4 , 3 , 6 , 8 , 10 , 7 , 9 ]
n = len (arr)
print ( "Index of the element is" , findElement(arr, n))
|
C#
using System;
public class MainClass {
public static bool Check( int [] arr, int n, int ind)
{
int i = ind - 1;
int j = ind + 1;
while (i >= 0) {
if (arr[i] > arr[ind]) {
return false ;
}
i--;
}
while (j < n) {
if (arr[j] < arr[ind]) {
return false ;
}
j++;
}
return true ;
}
public static int FindElement( int [] arr, int n)
{
for ( int i = 1; i < n - 1; i++) {
if (Check(arr, n, i)) {
return i;
}
}
return -1;
}
public static void Main()
{
int [] arr = { 5, 1, 4, 3, 6, 8, 10, 7, 9 };
int n = arr.Length;
Console.WriteLine( "Index of the element is "
+ FindElement(arr, n));
}
}
|
Javascript
function check(arr, n, ind) {
let i = ind - 1;
let j = ind + 1;
while (i >= 0) {
if (arr[i] > arr[ind]) {
return false ;
}
i--;
}
while (j < n) {
if (arr[j] < arr[ind]) {
return false ;
}
j++;
}
return true ;
}
function findElement(arr, n) {
for (let i = 1; i < n - 1; i++) {
if (check(arr, n, i)) {
return i;
}
}
return -1;
}
let arr = [5, 1, 4, 3, 6, 8, 10, 7, 9];
let n = arr.length;
console.log( "Index of the element is " + findElement(arr, n));
|
Output
Index of the element is 4
Time Complexity: O(n2), Time complexity of the given program is O(n^2) as there are two nested while loops in the check function, which are iterating over at most n-2 elements each, and they are being called for each element in the array except the first and last elements.
Auxiliary Space: O(1), Space complexity of the program is O(1) as no extra space is being used, except for the input array and some integer variables used for indexing and loop control.
An Efficient Solution can solve this problem in O(n) time using O(n) extra space. Below is the detailed solution.
- Create two arrays leftMax[] and rightMin[].
- Traverse input array from left to right and fill leftMax[] such that leftMax[i] contains a maximum element from 0 to i-1 in the input array.
- Traverse input array from right to left and fill rightMin[] such that rightMin[i] contains a minimum element from to n-1 to i+1 in the input array.
- 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.
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 the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findElement( int arr[], int n)
{
int leftMax[n];
leftMax[0] = INT_MIN;
for ( int i = 1; i < n; i++)
leftMax[i] = max(leftMax[i-1], arr[i-1]);
int rightMin = INT_MAX;
for ( int i=n-1; i>=0; i--)
{
if (leftMax[i] < arr[i] && rightMin > arr[i])
return i;
rightMin = min(rightMin, arr[i]);
}
return -1;
}
int main()
{
int arr[] = {5, 1, 4, 3, 6, 8, 10, 7, 9};
int n = sizeof arr / sizeof arr[0];
cout << "Index of the element is " << findElement(arr, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
static int findElement( int [] arr, int n)
{
int [] leftMax = new int [n];
leftMax[ 0 ] = Integer.MIN_VALUE;
for ( int i = 1 ; i < n; i++)
leftMax[i] = Math.max(leftMax[i - 1 ], arr[i - 1 ]);
int rightMin = Integer.MAX_VALUE;
for ( int i = n - 1 ; i >= 0 ; i--)
{
if (leftMax[i] < arr[i] && rightMin > arr[i])
return i;
rightMin = Math.min(rightMin, arr[i]);
}
return - 1 ;
}
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));
}
}
|
Python3
def findElement(arr, n):
leftMax = [ None ] * n
leftMax[ 0 ] = arr[ 0 ]
for i in range ( 1 , n):
leftMax[i] = max (leftMax[i - 1 ], arr[i - 1 ])
rightMin = [ None ] * n
rightMin[n - 1 ] = arr[n - 1 ]
for i in range (n - 2 , - 1 , - 1 ):
rightMin[i] = min (rightMin[i + 1 ], arr[i])
for i in range ( 1 , n - 1 ):
if leftMax[i - 1 ] < = arr[i] and arr[i] < = rightMin[i + 1 ]:
return i
return - 1
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))
|
C#
using System;
class GFG
{
static int findElement( int [] arr, int n)
{
int [] leftMax = new int [n];
leftMax[0] = int .MinValue;
for ( int i = 1; i < n; i++)
leftMax[i] = Math.Max(leftMax[i - 1], arr[i - 1]);
int rightMin = int .MaxValue;
for ( int i=n-1; i>=0; i--)
{
if (leftMax[i] < arr[i] && rightMin > arr[i])
return i;
rightMin = Math.Min(rightMin, arr[i]);
}
return -1;
}
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));
}
}
|
PHP
<?php
function findElement( $arr , $n )
{
$leftMax = array (0);
$leftMax [0] = PHP_INT_MIN;
for ( $i = 1; $i < $n ; $i ++)
$leftMax [ $i ] = max( $leftMax [ $i - 1],
$arr [ $i - 1]);
$rightMin = PHP_INT_MAX;
for ( $i = $n - 1; $i >= 0; $i --)
{
if ( $leftMax [ $i ] < $arr [ $i ] &&
$rightMin > $arr [ $i ])
return $i ;
$rightMin = min( $rightMin , $arr [ $i ]);
}
return -1;
}
$arr = array (5, 1, 4, 3, 6, 8, 10, 7, 9);
$n = count ( $arr );
echo "Index of the element is " ,
findElement( $arr , $n );
?>
|
Javascript
<script>
function findElement(arr, n)
{
var leftMax = Array(n).fill(0);
leftMax[0] = Number.MIN_VALUE;
for (i = 1; i < n; i++)
leftMax[i] = Math.max(leftMax[i - 1],
arr[i - 1]);
var rightMin = Number.MAX_VALUE;
for (i = n - 1; i >= 0; i--)
{
if (leftMax[i] < arr[i] &&
rightMin > arr[i])
return i;
rightMin = Math.min(rightMin, arr[i]);
}
return -1;
}
var arr = [ 5, 1, 4, 3, 6, 8, 10, 7, 9 ];
var n = arr.length;
document.write( "Index of the element is " +
findElement(arr, n));
</script>
|
Output:
Index of the element is 4
Time Complexity: O(n), The program uses two loops to traverse the input array, one from left to right and another from right to left. The time complexity of the first loop is O(n) and that of the second loop is also O(n), so the overall time complexity of the program is O(n).
Auxiliary Space: O(n), The program uses an extra array of size n to store the maximum of all left elements, so the space complexity of the program is O(n).
Thanks to Gaurav Ahirwar for suggesting the above solution.
Space Optimized Approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findElement( int a[], int n)
{
if (n == 1 || n == 2) {
return -1;
}
int element = a[0], maxx = a[0], bit = -1, check = 0;
int idx = -1;
for ( int i = 1; i < (n - 1);) {
if (a[i] < maxx && i < (n - 1)) {
i++;
bit = 0;
}
else {
if (a[i] >= maxx) {
element = a[i];
idx = i;
check = 1;
maxx = a[i];
}
if (check == 1) {
i++;
}
bit = 1;
while (a[i] >= element && i < (n - 1)) {
if (a[i] > maxx) {
maxx = a[i];
}
i++;
}
check = 0;
}
}
if (element <= a[n - 1] && bit == 1) {
return idx;
}
else {
return -1;
}
}
int main()
{
int arr[] = { 5, 1, 4, 3, 6, 8, 10, 7, 9 };
int n = sizeof arr / sizeof arr[0];
cout << "Index of the element is "
<< findElement(arr, n);
return 0;
}
|
Java
class GFG{
static int findElement( int []a, int n)
{
if (n == 1 || n == 2 )
{
return - 1 ;
}
int element = a[ 0 ], maxx = a[ 0 ],
bit = - 1 , check = 0 ;
int idx = - 1 ;
for ( int i = 1 ; i < (n - 1 );)
{
if (a[i] < maxx && i < (n - 1 ))
{
i++;
bit = 0 ;
}
else
{
if (a[i] >= maxx)
{
element = a[i];
idx = i;
check = 1 ;
maxx = a[i];
}
if (check == 1 )
{
i++;
}
bit = 1 ;
while (a[i] >= element && i < (n - 1 ))
{
if (a[i] > maxx)
{
maxx = a[i];
}
i++;
}
check = 0 ;
}
}
if (element <= a[n - 1 ] && bit == 1 )
{
return idx;
}
else
{
return - 1 ;
}
}
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));
}
}
|
Python3
def findElement (a, n):
if (n = = 1 or n = = 2 ):
return - 1
element, maxx, bit = a[ 0 ], a[ 0 ], - 1
check = 0
idx = - 1
i = 1
while (i < (n - 1 )):
if (a[i] < maxx and i < (n - 1 )):
i + = 1
bit = 0
else :
if (a[i] > = maxx):
element = a[i]
idx = i
check = 1
maxx = a[i]
if (check = = 1 ):
i + = 1
bit = 1
while (a[i] > = element and i < (n - 1 )):
if (a[i] > maxx):
maxx = a[i]
i + = 1
check = 0
if (element < = a[n - 1 ] and bit = = 1 ):
return idx
else :
return - 1
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))
|
C#
using System;
class GFG{
static int findElement( int []a, int n)
{
if (n == 1 || n == 2)
{
return -1;
}
int element = a[0], maxx = a[0],
bit = -1, check = 0;
int idx = -1;
for ( int i = 1; i < (n - 1);)
{
if (a[i] < maxx && i < (n - 1))
{
i++;
bit = 0;
}
else
{
if (a[i] >= maxx)
{
element = a[i];
idx = i;
check = 1;
maxx = a[i];
}
if (check == 1)
{
i++;
}
bit = 1;
while (a[i] >= element && i < (n - 1))
{
if (a[i] > maxx)
{
maxx = a[i];
}
i++;
}
check = 0;
}
}
if (element <= a[n - 1] && bit == 1)
{
return idx;
}
else
{
return -1;
}
}
public static void Main( string [] args)
{
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));
}
}
|
Javascript
<script>
function findElement(a , n)
{
if (n == 1 || n == 2)
{
return -1;
}
var element = a[0], maxx = a[0], bit = -1, check = 0;
var idx = -1;
for (i = 1; i < (n - 1);) {
if (a[i] < maxx && i < (n - 1)) {
i++;
bit = 0;
}
else {
if (a[i] >= maxx) {
element = a[i];
idx = i;
check = 1;
maxx = a[i];
}
if (check == 1) {
i++;
}
bit = 1;
while (a[i] >= element && i < (n - 1)) {
if (a[i] > maxx) {
maxx = a[i];
}
i++;
}
check = 0;
}
}
if (element <= a[n - 1] && bit == 1)
{
return idx;
}
else
{
return -1;
}
}
var arr = [ 5, 1, 4, 3, 6, 8, 10, 7, 9 ];
var n = arr.length;
document.write( "Index of the element is " + findElement(arr, n));
</script>
|
Output
Index of the element is 4
Time Complexity: O(n), The time complexity of this program is O(n) where n is the size of the input array. This is because the program iterates through the array only once to find the element that satisfies the given condition.
Auxiliary Space: O(1), The space complexity of this program is O(1) because it uses only a constant amount of extra space to store some variables like element, maxx, bit, check, and idx, which are not dependent on the input size. Therefore, the space used by the program does not increase with the size of the input array.
Please Login to comment...