Given a circular integer array, find the next greater element for every element in it. The next greater element of an element x in the array is the first larger number to the next of x.

In a circular array, the indices will wrap around as if it were connected end-to-end. In other words, the end of the array wraps around to the start of the array. Therefore, we can search circularly to find the next greater number. If the next greater element doesn’t exist, consider it to be -1.

 
For example,

Input:  [3, 5, 2, 4]
Output: [5, -1, 4, 5]
 
Input:  [7, 5, 3, 4]
Output: [-1, 7, 4, 7]

Practice this problem

 
Related Post:

Find the next greater element for every array element

 
In the above post, we have discussed finding the next greater element for every element in a “normal” array. We can easily extend the solution for “circular” arrays as well, just by looping twice. We can do this by doubling the loop counter and taking the modulo of loop counter indices with n.

 
The core idea remains the same – for each element x, pop elements that are smaller than x, and set their next greater element to x. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

5 -1 4 5

Java


Download  Run Code

Output:

[5, -1, 4, 5]

Python


Download  Run Code

Output:

[5, -1, 4, 5]

Note that each element is pushed and popped at most once. Therefore, the time complexity of the above solution is O(n), where n is the input size and requires O(n) extra space for the stack.

 
We can also process array elements from right to left. The idea is for each element x, loop till we have a greater element on top of the stack or the stack gets empty. When the stack gets a greater element on top, set it as the next greater element of x. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

5 -1 4 5

Java


Download  Run Code

Output:

[5, -1, 4, 5]

Python


Download  Run Code

Output:

[5, -1, 4, 5]