Given a circular integer array nums, return the next greater number for every element. Search circularly if needed. Return -1 if no greater element exists.
Java
Next Greater Element II
Given a circular integer array nums, return the next greater number for every element. Search circularly if needed. Return -1 if no greater element exists.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Input
arr =[1,2,1]
Initialize result with -1. We'll iterate 2*n = 6 times for circular handling.
Circular Array (wraps around)
...
1
2
1
...
0
1
2
Stack (indices)
Result
-1
-1
-1
0
1
2
Algorithm Insight:
Iterate 2n times using modulo for circular access. Use monotonic decreasing stack to track indices waiting for a greater element. When found, update their result.