Write Python Program to Find Greater Element

In this tutorial, we will write the Python program to find the greater element in the given list. A greater element means an element in the array is the nearest element on the right, greater than the current element. Let's see the problem statement.

Problem Statement

Given an array arr[] of size N, the task is to find the next greater element for each element of the array in the order of their appearance in the array. If there is no greater element of the current element, then next greater element for current element is -1.

Example -

Solution -

We can solve it using the stack data- structure. Let's understand the following example.

Example -

Output:

[3, 4, 4, -1]

Explanation -

In the above code, we initialize an empty stack and a result list of size N, where each element is initially set to -1.

Next, we loop through the array arr[] from left to right. For each element arr[i], we compare it with the top element of the stack. If arr[i] is greater than the top element, we pop the index from the stack and set the corresponding element in the result list to arr[i]. We continue this process until either the stack is empty or the top element is greater than arr[i].

After processing each element in arr[], the result list will contain the next greater element for each element of the array in the order of their appearance in the array. If an element does not have a next greater element, its corresponding value in the result list will remain -1.

Method - 2: Brute-Force Approach

In this approach, we use the nested loop and compare each element with the elements to its right until a greater element is found. The algorithm is given below.

Algorithm -

  1. Traverse the given array from left to right.
  2. For each element arr[i], traverse the subarray arr[i+1] to arr[N-1] to find the next greater element.
  3. If a greater element is found, assign it to the variable next greater and break the inner loop.
  4. If no greater element is found, assign -1 to the variable next greater.
  5. Print the value of next greater for each element.

Let's understand the following code.

Example -

Output:

5 25 25 -1 -1 -1





Latest Courses