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.
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.
We can solve it using the stack data- structure. Let's understand the following example.
[3, 4, 4, -1]
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.
Let's understand the following code.
5 25 25 -1 -1 -1
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week