Write Python Program to Find Greater ElementIn 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 StatementGiven 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 ApproachIn 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 -
Let's understand the following code. Example - Output: 5 25 25 -1 -1 -1 |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India