Find the Next Greater Element for Every ElementIn this tutorial, we will write the Python program to find the next greater element for every element in the given array. The "Next Greater Element" for a given element x refers to the first element on the right side of x in the array that is greater than x. If there is no greater element to the right of x, it is considered as -1. Let's understand the following example - Example: Input: arr[] = [3, 8, 4, 10, 6] Output: 3 -> 8 8 -> 10 4 -> 10 10 -> -1 6 -> -1 Explanation: In this example, for each element in the array, we find the next greater element on its right side. The output shows the mapping of elements to their next greater elements. Elements 10 and 6 don't have any greater elements on their right side. Solution - 1:In this approach, we will use the two for loops, the outer loop will traverse the elements one by one and the inner loop checks the first greater element for the element picked by the outer loop. Then we check the condition if a greater element is found then that element is printed as next, otherwise, -1 is printed. Let's understand the following example - Example - Output 11 --> 13 13 --> 21 21 --> -1 3 --> -1 Explanation - In the above code, we have followed the below steps -
Time Complexity: O(N2) Auxiliary Space: O(1) Solution - 2: Find Next Greater Element using StackThe concept involves using a stack to keep track of elements for which we need to find the next greater element. While iterating through the array, when we encounter a greater element, we'll associate it with the elements from the stack until the top element of the stack is smaller than the current element. Let's understand the following example - Example - Output [5, 10, 10, -1, -1] ConclusionIn this tutorial, we explored two solutions for finding the next greater element for each element in an array. The first solution used nested loops with a time complexity of O(N^2), while the second solution employed a stack, resulting in a more efficient O(N) time complexity. Using a stack is a practical approach for solving such problems, offering improved performance. Next TopicFind-the-next-greater-frequency-element |
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