The Wayback Machine - https://web.archive.org/web/20240907010843/https://www.geeksforgeeks.org/previous-greater-element/
Open In App

Previous greater element

Last Updated : 26 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Expected time complexity : O(n)

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.

Implementation:

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);
}
}


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.
     
?>


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>


Output

-1, 10, 4, -1, -1, 40, 40, 

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

Smallest subarray of size greater than K with sum greater than a given value
Given an array, arr[] of size N, two positive integers K and S, the task is to find the length of the smallest subarray of size greater than K, whose sum is greater than S. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 1, S = 8Output: 2Explanation: Smallest subarray with sum greater than S(=8) is {4, 5}Therefore, the required output is 2. Input: ar
15 min read
Count greater elements on the left side of every array element
Given an array arr[] of distinct integers of size N, the task is to print the count of greater elements on the left side of each array element. Examples : Input: arr[] = {12, 1, 2, 3, 0, }Output: 0 1 1 1 4Explanation:For index 0, no greater element exists on the left side.For index 1, {12} is greater element on the left side.For index 2, {12} is gr
7 min read
Adding elements of an array until every element becomes greater than or equal to k
We are given a list of N unsorted elements, we need to find the minimum number of steps in which the elements of the list can be added to make all the elements greater than or equal to K. We are allowed to add two elements together and make them one. Examples: Input: arr[] = {1 10 12 9 2 3} K = 6 Output: 2 Explanation: First we add (1 + 2), now the
15+ min read
Previous Solved CS Papers Year wise - GATE / UGC / ISRO
Here, we have listed all these important solved year wise papers. We have tried to solve these paper with best and errorless explanations. We have also provided alternative explanation or more than one methods to solve a specific question whenever possible. You can practice them online with prior knowledge to solve and learn them by understanding i
2 min read
Smallest number in BST which is greater than or equal to N ( Iterative Approach)
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Examples: Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST
8 min read
Split Array into min number of subsets with difference between each pair greater than 1
Given an array arr[] of size N, the task is to split the array into a minimum number of subset such that each pair of elements in each subset have the difference strictly greater than 1.Note: All elements in the array are distinct. Examples: Input: arr = {5, 10, 6, 50}Output: 2Explanation: Possible partitions are: {5, 10, 50}, {6} Input: arr = {2,
5 min read
Find the greater number closest to N having at most one non-zero digit
Given an integer N, the task is to find the closest number to N which is greater than N and contains at most one non-zero digit. Examples: Input: N = 540Output: 600Explanation: Since the number 600 contains only one non-zero digit, it is the required output is 600. Input: N = 1000Output: 2000 Approach: The problem can be solved based on the followi
9 min read
Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1s is always greater than 0s from left
Given a binary string S(1-based indexing) of size N, and two positive integers K1 and K2, the task is to find the lexicographically smallest string by flipping the characters at indices that are not divisible by either K1 or K2 such that the count of 1s till every possible index is always greater than the count of 0s. If it is not possible to form
8 min read
Find N distinct integers with GCD of sequence as 1 and GCD of each pair greater than 1
Given an integer N, the task is to find a sequence of N distinct positive integers such that the Greatest Common Divisor of the sequence is 1 and GCD of all possible pairs of elements is greater than 1. Input: N = 4Output: 84 60 105 70Explanation: The GCD(84, 60, 105, 70) is 1 and the GCD of all possible pair of elements i.e, {(84, 60), (84, 105),
5 min read
Rearrange array such that even index elements are smaller and odd index elements are greater
Given an array, rearrange the array such that : If index i is even, arr[i] &lt;= arr[i+1]If index i is odd, arr[i] &gt;= arr[i+1] Note: There can be multiple answers. Examples: Input : arr[] = {2, 3, 4, 5} Output : arr[] = {2, 4, 3, 5} Explanation : Elements at even indexes are smaller and elements at odd indexes are greater than their next element
11 min read
Count greater nodes in AVL tree
In this article we will see that how to calculate number of elements which are greater than given value in AVL tree. Examples: Input : x = 5 Root of below AVL tree 9 / \ 1 10 / \ \ 0 5 11 / / \ -1 2 6 Output : 4 Explanation: there are 4 values which are greater than 5 in AVL tree which are 6, 9, 10 and 11. Prerequisites : Insertion in AVL treeDelet
15+ min read
Last element of an array after repeatedly removing the first element and appending it to the end of the array twice exactly K times
Given an array arr[] consisting of N integers and a positive integer K, the task is to find the last element present in the array obtained by repeatedly removing the first element of the array and appending it twice to the end of the array K times. Examples: Input: arr[] = {1, 2, 3, 4, 5}, K = 5Output: 5Explanation:Initially, the array is {1, 2, 3,
7 min read
Remaining array element after repeated removal of the smallest element from pairs with absolute difference of 2 or 0
Given an array arr[] consisting of N positive integers, the task is to check if it is possible to reduce the size of the array to 1 by repeatedly removing the smallest element from a pair having absolute difference of 2 or 0 between them. If it is not possible to reduce, then print "-1". Otherwise, print the last remaining element in the array. Exa
6 min read
Minimize replacements to make every element in an array exceed every element in another given array
Given two arrays A[] and B[] of size N and M respectively, where each element is in the range [0, 9], the task is to make each element of the array A[] strictly greater than or smaller than every element in the array B[] by changing any element from either array to any number in the range [0, 9], minimum number of times. Examples: Input: A[] = [0,
10 min read
Check if an array has a majority element
Given an array, the task is to find if the input array contains a majority element or not. An element is Examples: Input : arr[] = {2, 3, 9, 2, 2} Output : Yes A majority element 2 is present in arr[] Input : arr[] = {1, 8, 9, 2, 5} Output : No A simple solution is to traverse through the array. For every element, count its occurrences. If the coun
4 min read
Last element of vector in C++ (Accessing and updating)
In C++ vectors, we can access last element using size of vector using following ways. 1) Using size() #include &lt;bits/stdc++.h&gt; using namespace std; int main() { vector&lt;int&gt; v{10, 20, 30, 40, 50}; // Accessing last element int n = v.size(); cout &lt;&lt; v[n - 1] &lt;&lt; endl; // modifying last element v[n - 1] = 100; cout &lt;&lt; v[n
1 min read
Most frequent element in an array
Given an array, find the most frequent element in it. If there are multiple elements that appear a maximum number of times, print any one of them. Examples: Input : arr[] = {1, 3, 2, 1, 4, 1}Output : 1Explanation: 1 appears three times in array which is maximum frequency. Input : arr[] = {10, 20, 10, 20, 30, 20, 20}Output : 20 A simple solution is
14 min read
Least frequent element in an array
Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them. Examples : Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}Output : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Output : 10 or 20 or 30 A simple solution is to run tw
12 min read
Rank of an element in a stream
Given a stream of integers, look up the rank of a given integer x. The rank of an integer in-stream is "Total number of elements less than or equal to x (not including x)".If an element is not found in the stream or is the smallest in the stream, return -1. Examples: Input : arr[] = {10, 20, 15, 3, 4, 4, 1} x = 4; Output : Rank of 4 in stream is: 3
11 min read
Center element of matrix equals sums of half diagonals
Given a matrix of odd order i.e(5*5). Task is to check if the center element of the matrix is equal to the individual sum of all the half diagonals. Examples: Input : mat[][] = { 2 9 1 4 -2 6 7 2 11 4 4 2 9 2 4 1 9 2 4 4 0 2 4 2 5 } Output : Yes Explanation : Sum of Half Diagonal 1 = 2 + 7 = 9 Sum of Half Diagonal 2 = 9 + 0 = 9 Sum of Half Diagonal
7 min read
Find the closest element in Binary Search Tree | Space Efficient Method
Given a binary search tree and a target node K. The task is to find the node with the minimum absolute difference with given target value K. NOTE: The approach used should have constant extra space consumed O(1). No recursion or stack/queue like containers should be used. Examples: Input: k = 4 Output: 4 Input: k = 18 Output: 17 A simple solution m
10 min read
Find the element at the specified index of a Spirally Filled Matrix
Given two integers x and y representing the row and column number in a matrix respectively, the task is to find the integer at the cell (x, y) in the Spirally Filled Matrix. Explanation: The size of the matrix change according to the insertion of elements. As the row and columns are filled layer - by - layer, a square matrix will be formed as each
7 min read
Majority element in a circular array of 0's and 1's
Given a circular array containing only 0’s and 1’s, of size n where n = p*q (p and q are both odd integers). The task is to check if there is a way such that 1 will be in majority after applying the following operations: Divide circular array into p subarrays each of size q.In each subarray, the number which is in majority will get stored into arra
15+ min read
Number of sub-sequence such that it has one consecutive element with difference less than or equal to 1
Given an array arr[] of N elements. The task is to find the number of sub-sequences which have at least two consecutive elements such that absolute difference between them is ? 1. Examples: Input: arr[] = {1, 6, 2, 1} Output: 6 {1, 2}, {1, 2, 1}, {2, 1}, {6, 2, 1}, {1, 1} and {1, 6, 2, 1} are the sub-sequences that have at least one consecutive pai
7 min read
Minimize swaps to rearrange array such that parity of index and corresponding element is same
Given an array A[], the task to find minimum swapping operations required to modify the given array A[] such that for every index in the array, parity(i) = parity(A[i]) where parity(x) = x % 2. If it's impossible to obtain such an arrangement, then print -1. Examples: Input: A[] = { 2, 4, 3, 1, 5, 6 } Output: 2 Explanation: Swapping (4, 3) and (5,
6 min read
Check if an Array is made up of Subarrays of continuous repetitions of every distinct element
Given an array arr[], consisting of N integers, the task is to check whether the entire array is only made up of subarrays such that each subarray consists of consecutive repetitions of a single element and every distinct element in the array is part of such subarray. Examples: Input: N = 10, arr[] = {1, 1, 1, 1, 2, 2, 3, 3, 3, 3} Output: Yes Expla
11 min read
Count all distinct pairs of repeating elements from the array for every array element
Given an array arr[] of N integers. For each element in the array, the task is to count the possible pairs (i, j), excluding the current element, such that i &lt; j and arr[i] = arr[j]. Examples: Input: arr[] = {1, 1, 2, 1, 2}Output: 2 2 3 2 3Explanation:For index 1, remaining elements after excluding current element are [1, 2, 1, 2]. So the count
7 min read
Maximize count of subsets having product of smallest element and size of the subset at least X
Given an array arr[] consisting of N integers and an integer X, the task is to count the maximum number of subsets possible from the given array having Smallest element of the Subset * Size of the Subset ? X Examples: Input: arr[] = {7, 11, 2, 9, 5}, X = 10Output: 2Explanation: One of the possible solution is {7, 9} and {11, 5}. In subset {7, 9} th
6 min read
Maximum number of pairs of distinct array elements possible by including each element in only one pair
Given an array arr[] consisting of N integers, the task is to find the maximum number of pairs of array elements such that each pair has a different element and each array element can exist in only one pair Examples: Input: arr[] = {4, 5, 4, 5, 4}Output: 2Explanation:There can be 2 pairs forms from the given array i.e., {{4, 5}, {4, 5}}. Therefore,
12 min read
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other
Given an array arr[] and an integer K, the task is to find the minimum number of operations to make all the elements of the array arr[] equal. In one operation, K is subtracted from an element and this K is added into other element. If it is not possible then print -1. Examples: Input: arr[] = {5, 8, 11}, K = 3Output: 1Explanation:Operation 1: Subt
7 min read
Article Tags :
Practice Tags :