Given an array of distinct elements, find previous greater element for every element. If previous greater element does not exist, print -1.
Examples:
Input : arr[] = {10, 4, 2, 20, 40, 12, 30}
Output : -1, 10, 4, -1, -1, 40, 40
Input : arr[] = {10, 20, 30, 40}
Output : -1, -1, -1, -1
Input : arr[] = {40, 30, 20, 10}
Output : -1, 40, 30, 20
[Naive Solution] - Nested Loops - O(n^2) Time and O(1) Space
A simple solution is to run two nested loops. The outer loop picks an element one by one. The inner loop, find the previous element that is greater.
C++
// C++ program previous greater element
// A naive solution to print previous greater
// element for every element in an array.
#include <bits/stdc++.h>
using namespace std;
void prevGreater(int arr[], int n)
{
// Previous greater for first element never
// exists, so we print -1.
cout << "-1, ";
// Let us process remaining elements.
for (int i = 1; i < n; i++) {
// Find first element on left side
// that is greater than arr[i].
int j;
for (j = i-1; j >= 0; j--) {
if (arr[i] < arr[j]) {
cout << arr[j] << ", ";
break;
}
}
// If all elements on left are smaller.
if (j == -1)
cout << "-1, ";
}
}
// Driver code
int main()
{
int arr[] = { 10, 4, 2, 20, 40, 12, 30 };
int n = sizeof(arr) / sizeof(arr[0]);
prevGreater(arr, n);
return 0;
}
Java
// Java program previous greater element
// A naive solution to print
// previous greater element
// for every element in an array.
import java.io.*;
import java.util.*;
import java.lang.*;
class GFG
{
static void prevGreater(int arr[],
int n)
{
// Previous greater for
// first element never
// exists, so we print -1.
System.out.print("-1, ");
// Let us process
// remaining elements.
for (int i = 1; i < n; i++)
{
// Find first element on
// left side that is
// greater than arr[i].
int j;
for (j = i-1; j >= 0; j--)
{
if (arr[i] < arr[j])
{
System.out.print(arr[j] + ", ");
break;
}
}
// If all elements on
// left are smaller.
if (j == -1)
System.out.print("-1, ");
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = {10, 4, 2, 20, 40, 12, 30};
int n = arr.length;
prevGreater(arr, n);
}
}
Python 3
# Python 3 program previous greater element
# A naive solution to print previous greater
# element for every element in an array.
def prevGreater(arr, n) :
# Previous greater for first element never
# exists, so we print -1.
print("-1",end = ", ")
# Let us process remaining elements.
for i in range(1, n) :
flag = 0
# Find first element on left side
# that is greater than arr[i].
for j in range(i-1, -1, -1) :
if arr[i] < arr[j] :
print(arr[j],end = ", ")
flag = 1
break
# If all elements on left are smaller.
if j == 0 and flag == 0:
print("-1",end = ", ")
# Driver code
if __name__ == "__main__" :
arr = [10, 4, 2, 20, 40, 12, 30]
n = len(arr)
prevGreater(arr, n)
# This code is contributed by ANKITRAI1
C#
// C# program previous greater element
// A naive solution to print
// previous greater element
// for every element in an array.
using System;
class GFG
{
static void prevGreater(int[] arr,
int n)
{
// Previous greater for
// first element never
// exists, so we print -1.
Console.Write("-1, ");
// Let us process
// remaining elements.
for (int i = 1; i < n; i++)
{
// Find first element on
// left side that is
// greater than arr[i].
int j;
for (j = i-1; j >= 0; j--)
{
if (arr[i] < arr[j])
{
Console.Write(arr[j] + ", ");
break;
}
}
// If all elements on
// left are smaller.
if (j == -1)
Console.Write("-1, ");
}
}
// Driver Code
public static void Main()
{
int[] arr = {10, 4, 2, 20, 40, 12, 30};
int n = arr.Length;
prevGreater(arr, n);
}
}
JavaScript
<script>
// Javascript program previous greater element
// A naive solution to print
// previous greater element
// for every element in an array.
function prevGreater(arr,n)
{
// Previous greater for
// first element never
// exists, so we print -1.
document.write("-1, ");
// Let us process
// remaining elements.
for (let i = 1; i < n; i++)
{
// Find first element on
// left side that is
// greater than arr[i].
let j;
for (j = i-1; j >= 0; j--)
{
if (arr[i] < arr[j])
{
document.write(arr[j] + ", ");
break;
}
}
// If all elements on
// left are smaller.
if (j == -1)
document.write("-1, ");
}
}
// Driver Code
let arr=[10, 4, 2, 20, 40, 12, 30];
let n = arr.length;
prevGreater(arr, n);
// This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// php program previous greater element
// A naive solution to print previous greater
// element for every element in an array.
function prevGreater(&$arr,$n)
{
// Previous greater for first element never
// exists, so we print -1.
echo( "-1, ");
// Let us process remaining elements.
for ($i = 1; $i < $n; $i++)
{
// Find first element on left side
// that is greater than arr[i].
for ($j = $i-1; $j >= 0; $j--)
{
if ($arr[$i] < $arr[$j])
{
echo($arr[$j]);
echo( ", ");
break;
}
}
// If all elements on left are smaller.
if ($j == -1)
echo("-1, ");
}
}
// Driver code
$arr = array(10, 4, 2, 20, 40, 12, 30);
$n = sizeof($arr) ;
prevGreater($arr, $n);
//This code is contributed by Shivi_Aggarwal.
?>
Output-1, 10, 4, -1, -1, 40, 40,
[Expected Solution] - O(n) Time and O(n) Space
An efficient solution is to use stack data structure. If we take a closer look, we can notice that this problem is a variation of stock span problem. We maintain previous greater element in a stack.
C++
// C++ program previous greater element
// An efficient solution to print previous greater
// element for every element in an array.
#include <bits/stdc++.h>
using namespace std;
void prevGreater(int arr[], int n)
{
// Create a stack and push index of first element
// to it
stack<int> s;
s.push(arr[0]);
// Previous greater for first element is always -1.
cout << "-1, ";
// Traverse remaining elements
for (int i = 1; i < n; i++) {
// Pop elements from stack while stack is not empty
// and top of stack is smaller than arr[i]. We
// always have elements in decreasing order in a
// stack.
while (s.empty() == false && s.top() < arr[i])
s.pop();
// If stack becomes empty, then no element is greater
// on left side. Else top of stack is previous
// greater.
s.empty() ? cout << "-1, " : cout << s.top() << ", ";
s.push(arr[i]);
}
}
// Driver code
int main()
{
int arr[] = { 10, 4, 2, 20, 40, 12, 30 };
int n = sizeof(arr) / sizeof(arr[0]);
prevGreater(arr, n);
return 0;
}
Java
// Java program previous greater element
// An efficient solution to
// print previous greater
// element for every element
// in an array.
import java.io.*;
import java.util.*;
import java.lang.*;
class GFG
{
static void prevGreater(int arr[],
int n)
{
// Create a stack and push
// index of first element
// to it
Stack<Integer> s = new Stack<Integer>();
s.push(arr[0]);
// Previous greater for
// first element is always -1.
System.out.print("-1, ");
// Traverse remaining elements
for (int i = 1; i < n; i++)
{
// Pop elements from stack
// while stack is not empty
// and top of stack is smaller
// than arr[i]. We always have
// elements in decreasing order
// in a stack.
while (s.empty() == false &&
s.peek() < arr[i])
s.pop();
// If stack becomes empty, then
// no element is greater on left
// side. Else top of stack is
// previous greater.
if (s.empty() == true)
System.out.print("-1, ");
else
System.out.print(s.peek() + ", ");
s.push(arr[i]);
}
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 10, 4, 2, 20, 40, 12, 30 };
int n = arr.length;
prevGreater(arr, n);
}
}
Python3
# Python3 program to print previous greater element
# An efficient solution to print previous greater
# element for every element in an array.
import math as mt
def prevGreater(arr, n):
# Create a stack and push index of
# first element to it
s = list();
s.append(arr[0])
# Previous greater for first element
# is always -1.
print("-1, ", end = "")
# Traverse remaining elements
for i in range(1, n):
# Pop elements from stack while stack is
# not empty and top of stack is smaller
# than arr[i]. We always have elements in
# decreasing order in a stack.
while (len(s) > 0 and s[-1] < arr[i]):
s.pop()
# If stack becomes empty, then no element
# is greater on left side. Else top of stack
# is previous greater.
if len(s) == 0:
print("-1, ", end = "")
else:
print(s[-1], ", ", end = "")
s.append(arr[i])
# Driver code
arr = [ 10, 4, 2, 20, 40, 12, 30 ]
n = len(arr)
prevGreater(arr, n)
# This code is contributed by
# mohit kumar 29
C#
// C# program previous greater element
// An efficient solution to
// print previous greater
// element for every element
// in an array.
using System;
using System.Collections.Generic;
class GFG
{
static void prevGreater(int []arr,
int n)
{
// Create a stack and push
// index of first element
// to it
Stack<int> s = new Stack<int>();
s.Push(arr[0]);
// Previous greater for
// first element is always -1.
Console.Write("-1, ");
// Traverse remaining elements
for (int i = 1; i < n; i++)
{
// Pop elements from stack
// while stack is not empty
// and top of stack is smaller
// than arr[i]. We always have
// elements in decreasing order
// in a stack.
while (s.Count != 0 &&
s.Peek() < arr[i])
s.Pop();
// If stack becomes empty, then
// no element is greater on left
// side. Else top of stack is
// previous greater.
if (s.Count == 0)
Console.Write("-1, ");
else
Console.Write(s.Peek() + ", ");
s.Push(arr[i]);
}
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 10, 4, 2, 20, 40, 12, 30 };
int n = arr.Length;
prevGreater(arr, n);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program previous greater element
// An efficient solution to
// print previous greater
// element for every element
// in an array.
function prevGreater(arr,n)
{
// Create a stack and push
// index of first element
// to it
let s = [];
s.push(arr[0]);
// Previous greater for
// first element is always -1.
document.write("-1, ");
// Traverse remaining elements
for (let i = 1; i < n; i++)
{
// Pop elements from stack
// while stack is not empty
// and top of stack is smaller
// than arr[i]. We always have
// elements in decreasing order
// in a stack.
while (s.length!=0 &&
s[s.length-1] < arr[i])
s.pop();
// If stack becomes empty, then
// no element is greater on left
// side. Else top of stack is
// previous greater.
if (s.length==0)
document.write("-1, ");
else
document.write(s[s.length-1] + ", ");
s.push(arr[i]);
}
}
// Driver Code
let arr=[10, 4, 2, 20, 40, 12, 30];
let n = arr.length;
prevGreater(arr, n);
// This code is contributed by rag2127
</script>
Output-1, 10, 4, -1, -1, 40, 40,
Complexity Analysis:
- Time Complexity: O(n). It seems more than O(n) at first look. If we take a closer look, we can observe that every element of array is added and removed from stack at most once. So there are total 2n operations at most. Assuming that a stack operation takes O(1) time, we can say that the time complexity is O(n).
- Auxiliary Space: O(n) in worst case when all elements are sorted in decreasing order.
Similar Reads
CSS Pseudo Elements
A pseudo-element is a keyword added to a selector that lets you style specific parts of an element. For example, you can style the first line of a paragraph, add content before or after an element, or create complex effects with minimal code. Pseudo-elements are denoted by a double colon (::) (or :
4 min read
Java Vector elements() Method
In Java, the elements() method is used to return an enumeration of the elements in the Vector. This method allows you to iterate over the elements of a Vector using an Enumeration, which provides methods for checking if there are more elements and retrieving the next element.Example 1: Below is the
2 min read
Java Vector elementAt() Method
In Java, the elementAt() method is used to fetch or retrieve an element at a specific index from a Vector. It allows to access elements in the vector by providing the index, which is zero-based.Example 1: Here, we use the elementAt() method to retrieve an element at a specified index with an Integer
2 min read
Vector lastElement() Method in Java
The java.util.vector.lastElement() method in Java is used to retrieve or fetch the last element of the Vector. It returns the element present at the last index of the vector. Syntax: Vector.lastElement() Parameters: The method does not take any parameter. Return Value: The method returns the last el
2 min read
Vector firstElement() Method in Java
The java.util.vector.firstElement() method in Java is used to retrieve or fetch the first element of the Vector. It returns the element present at the 0th index of the vector Syntax: Vector.firstElement() Parameters: The method does not take any parameter. Return Value: The method returns the first
2 min read
HTML | DOM Pre Object
The DOM Pre Object is used to represent the HTML <pre> element. The pre element is accessed by getElementById().Properties: width: It is used to set or return the value of the width attribute of the pre element. Syntax: document.getElementById("ID"); Where âidâ is the ID assigned to the âpreâ
1 min read
PHP prev() Function
The prev() function is an inbuilt function in PHP. It is used to return the immediate previous element from an array of the element which is currently pointed by the internal pointer. We have already discussed current() function in PHP. The current() function is used to return the value of the eleme
2 min read
std::prev in C++
std::prev returns an iterator pointing to the element after being advanced by certain number of positions in the reverse direction. It is defined inside the header file iterator. It returns a copy of the argument advanced by the specified amount in the backward direction. If it is a random-access it
5 min read
Vector insertElementAt() Method in Java with Examples
insertElementAt() method of Vector class present inside java.util package is used to insert a particular element at the specified index of the Vector. Both the element and the position are passed as the parameters. If an element is inserted at a specified index, then all the elements are pushed upwa
3 min read
Find the Previous Closest Smaller Node in a Singly Linked List
Given a singly linked list, the task is to find the previous closest smaller node for every node in a linked list. Examples: Input: 5 -> 6 -> 8 -> 2 -> 3 -> 4Output: -1 -> 5 -> 6 -> -1 -> 2 -> 3Explanation: For the first node 5, there is no previous closest smaller node
13 min read