![]() |
VOOZH | about |
Given an array arr[], find the Previous Greater Element (PGE) for every element in the array.
Examples:
Input: arr[] = [10, 4, 2, 20, 40, 12]
Output: [-1, 10, 4, -1, -1, 40]
Explanation:
For 10 → No elements on the left → -1
For 4 → Previous greater element is 10 → 10
For 2 → Previous greater element is 4 → 4
For 20 → No element on the left greater than 20 → -1
For 40 → No element on the left greater than 40 → -1
For 12 → Previous greater element is 40 → 40Input: arr[] = [10, 20, 30, 40]
Output: [-1, -1, -1, -1]
Explanation: Since the array is strictly increasing, no element has a greater element before it. Hence, all positions are assigned -1.
Table of Content
The idea is to use two loops: for each element, check the remaining elements on its right to find the next greater one. If none exists, store -1.
-1 10 4 -1 -1 40
The idea is to use a monotonic decreasing stack. We traverse the array from left to right. For each element, we pop elements from the stack that are smaller than or equal to it, since they cannot be the previous greater element. If the stack is not empty, the top of the stack is the previous greater element. Finally, we push the current element onto the stack.
-1 10 4 -1 -1 40