The Next Greater Element II problem gives you a circular array and asks for the next greater element for every position — wrapping around if needed. If no greater element exists in the entire array, return -1 for that position. This Next Greater Element II coding problem extends the monotonic stack to handle circular arrays.
Apple, Goldman Sachs, Microsoft, Meta, Amazon, Google, and Bloomberg ask this to test whether candidates can adapt the monotonic stack to circular arrays. The array, monotonic stack, and stack interview pattern is directly demonstrated, and the circular extension — doubling the array conceptually — is a key technique.
Monotonic stack with doubled iteration. Process the array twice (simulate circularity by iterating 2n times using i % n). In the first pass, build the stack. In the second pass, resolve remaining stack entries. Use a decreasing stack storing indices (not values) to correctly track positions in the result array.
Array: [3, 1, 2, 4]. Result: [-1, 2, 4, -1] (let's verify).
2n times for the circular pass (missing wrap-around).i directly instead of i % n when accessing array values.Circular array problems always use the "double the array" or "iterate 2n with modulo" trick. For circular next-greater, iterate 2n times, use i % n for array access, and push indices when not resolving the stack. After 2n iterations, remaining stack entries have no next greater (-1). Practice this circular extension for both next-greater and next-smaller variants on circular arrays.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum of Subarray Ranges | Medium | Solve | |
| Buildings With an Ocean View | Medium | Solve | |
| Daily Temperatures | Medium | Solve | |
| Count Bowl Subarrays | Medium | Solve | |
| Maximal Range That Each Element Is Maximum in It | Medium | Solve |