![]() |
VOOZH | about |
Given a circular array arr[], find the next greater element for each element in the array.
Note: The next greater element of an element is the first next element greater than it when traversing the array in order (circularly). If no such element exists, return -1 for that position.
Examples:
Input: arr[] = [5, 7, 1, 2, 6]
Output: [7, -1, 2, 6, 7]
Explanation:
Next greater element for 5 is 7.
For 7, no greater element exists, so it is -1.
For 1, the next greater element is 2.
For 2, the next greater element is 6.
For 6, the next greater element is 7 (circularly).Input: arr[] = [6, 8, 0, 1, 3]
Output: [8, -1, 1, 3, 6]
Explanation: In the array, the next larger element to 6 is 8, for 8 there is no larger elements hence it is -1, for 0 it is 1, for 1 it is 3 and then for 3 there is 6.
Table of Content
In a circular array, after reaching the n-th index, traversal continues again from index 0. To handle this, we can use the modulo operator. By iterating from index i to i + n and accessing elements as index % n, we can simulate circular traversal within the array itself. This allows us to process the circular nature of the array without using any extra space.
7 -1 2 6 7
We use the same ideas as next greater element in a normal array. Stack to find out the next greater element in linear time. We traverse the array from right to left. For each element, we remove elements from the stack that are smaller than or equal to it, as they cannot be the next greater element. If the stack is not empty after this, the top element of the stack is the next greater element for the current element. We then push the current element onto the stack.
Step By Step Implementations:
7 -1 2 6 7