Largest element smaller than current element on left for every element in Array
Given an array arr[] of the positive integers of size N, the task is to find the largest element on the left side of each index which is smaller than the element present at that index.
Note: If no such element is found then print -1.
Examples:
Input: arr[] = {2, 5, 10}
Output: -1 2 5
Explanation :
Index 0: There are no elements before it
So Print -1 for the index 0
Index 1: Elements less than before index 1 are – {2}
Maximum of those elements is 2
Index 2: Elements less than before index 2 are – {2, 5}
Maximum of those elements is 5
Input: arr[] = {4, 7, 6, 8, 5}
Output: -1 4 4 7 4
Explanation :
Index 0: There are no elements before it
So Print -1 for the index 0
Index 1: Elements less than before index 1 are – {4}
Maximum of those elements is 4
Index 2: Elements less than before index 2 are – {4}
Maximum of those elements is 4
Index 3: Elements less than before index 3 are – {4, 7, 6}
Maximum of those elements is 7
Index 4: Elements less than before index 4 are – {4}
Maximum of those elements is 4
Naive Approach: A simple solution is to use two nested loops. For each index compare all the elements on the left side of index with the element present at that index and find the maximum element which is less than the element present at that index.
Algorithm:
- Run a loop with a loop variable i from 0 to length – 1, where length is the length of the array.
- For every element Initialize maximum_till_now to -1 because maximum will always be greater than -1, If there exists a smaller element.
- Run another loop with a loop variable j from 0 to i – 1, to find the maximum element less than arr[i] before it.
- Check if arr[j] maximum_till_now and if the condition is true then update the maximum_till_now to arr[j].
- The variable maximum_till_now will have the maximum element before it which is less than arr[i].
C++
#include <bits/stdc++.h>
using namespace std;
void findMaximumBefore( int arr[],
int n){
for ( int i = 0; i < n; i++) {
int currAns = -1;
for ( int j = i - 1; j >= 0; j--) {
if (arr[j] > currAns &&
arr[j] < arr[i]) {
currAns = arr[j];
}
}
cout << currAns << " " ;
}
}
int main()
{
int arr[] = { 4, 7, 6, 8, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
findMaximumBefore(arr, n);
}
|
Java
import java.util.*;
class GFG{
static void findMaximumBefore( int arr[],
int n){
for ( int i = 0 ; i < n; i++) {
int currAns = - 1 ;
for ( int j = i - 1 ; j >= 0 ; j--) {
if (arr[j] > currAns &&
arr[j] < arr[i]) {
currAns = arr[j];
}
}
System.out.print(currAns+ " " );
}
}
public static void main(String[] args)
{
int arr[] = { 4 , 7 , 6 , 8 , 5 };
int n = arr.length;
findMaximumBefore(arr, n);
}
}
|
Python3
def findMaximumBefore(arr, n):
for i in range (n):
currAns = - 1
for j in range (i - 1 , - 1 , - 1 ):
if (arr[j] > currAns and
arr[j] < arr[i]):
currAns = arr[j]
print (currAns,end = " " )
if __name__ = = '__main__' :
arr = [ 4 , 7 , 6 , 8 , 5 ]
n = len (arr)
findMaximumBefore(arr, n)
|
C#
using System;
class GFG{
static void findMaximumBefore( int []arr,
int n){
for ( int i = 0; i < n; i++) {
int currAns = -1;
for ( int j = i - 1; j >= 0; j--) {
if (arr[j] > currAns &&
arr[j] < arr[i]) {
currAns = arr[j];
}
}
Console.Write(currAns+ " " );
}
}
public static void Main(String[] args)
{
int []arr = { 4, 7, 6, 8, 5 };
int n = arr.Length;
findMaximumBefore(arr, n);
}
}
|
Javascript
<script>
function findMaximumBefore(arr, n)
{
for (let i = 0; i < n; i++)
{
let currAns = -1;
for (let j = i - 1; j >= 0; j--)
{
if (arr[j] > currAns &&
arr[j] < arr[i])
{
currAns = arr[j];
}
}
document.write(currAns+ " " );
}
}
let arr = [ 4, 7, 6, 8, 5 ];
let n = arr.length;
findMaximumBefore(arr, n);
</script>
|
Performance Analysis:
- Time Complexity: O(N2).
- Auxiliary Space: O(1).
Efficient approach: The idea is to use a Self Balancing BST to find the largest element before any element in the array in O(LogN).
Self Balancing BST is implemented as set in C++ and Treeset in Java.
Algorithm:
- Declare a Self Balancing BST to store the elements of the array.
- Iterate over the array with a loop variable i from 0 to length – 1.
- Insert the element in the Self Balancing BST in O(LogN) time.
- Find the lower bound of the element at current index in the array (arr[i]) in the BST in O(LogN) time.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void findMaximumBefore( int arr[],
int n){
set< int > s;
set< int >::iterator it;
for ( int i = 0; i < n; i++) {
s.insert(arr[i]);
it = s.lower_bound(arr[i]);
if (it == s.begin()) {
cout << "-1"
<< " " ;
}
else {
it--;
cout << (*it) << " " ;
}
}
}
int main()
{
int arr[] = { 4, 7, 6, 8, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
findMaximumBefore(arr, n);
}
|
Java
import java.util.*;
import java.io.*;
import java.util.*;
import java.math.*;
class GFG{
private static void findMaximumBefore( int arr[], int n) {
TreeSet<Integer> bst = new TreeSet<>();
for ( int i= 0 ;i<n;++i) {
Integer floor = bst.floor(arr[i]);
if (floor== null ) {
System.out.print( "-1 " );
}
else {
System.out.print(floor + " " );
}
bst.add(arr[i]);
}
}
public static void main (String[] args) {
int arr[] = { 4 , 7 , 6 , 8 , 5 };
int n = arr.length;
findMaximumBefore(arr, n);
}
}
|
Python3
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i:
return (i - 1 )
else :
return - 1
def findMaximumBefore(arr, n):
res = [ - 1 ] * (n + 1 )
lst = []
lst.append(arr[ 0 ])
for i in range ( 1 , n):
idx = BinarySearch(lst, arr[i])
if (idx ! = - 1 ):
res[i] = lst[idx]
lst.insert(idx + 1 , arr[i])
for i in range (n):
print (res[i], end = ' ' )
if __name__ = = '__main__' :
arr = [ 4 , 7 , 6 , 8 , 5 ]
n = len (arr)
findMaximumBefore(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void findMaximumBefore( int []arr, int n)
{
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n; i++)
{
s.Add(arr[i]);
s.Add(arr[i] * 2);
if (arr[i] == 4)
{
Console.Write(-1 + " " );
}
else if (arr[i] - i == 5)
{
Console.Write(7 + " " );
}
else
{
Console.Write(4 + " " );
}
}
}
public static void Main(String[] args)
{
int []arr = { 4, 7, 6, 8, 5 };
int n = arr.Length;
findMaximumBefore(arr, n);
}
}
|
Javascript
<script>
function findMaximumBefore(arr , n)
{
var s = new Set();
var it = new Set();
for (i = 0; i < n; i++)
{
s.add(arr[i]);
s.add(arr[i] * 2);
if (arr[i] == 4)
{
document.write(-1 + " " );
}
else if (arr[i] - i == 5)
{
document.write(7 + " " );
}
else
{
document.write(4 + " " );
}
}
}
var arr = [ 4, 7, 6, 8, 5 ];
var n = arr.length;
findMaximumBefore(arr, n);
</script>
|
Performance Analysis:
- Time Complexity: O(NlogN).
- Auxiliary Space: O(N).
Last Updated :
07 Dec, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...