Next Greater Element II

medium array stack monotonic stack

Problem

Given a circular integer array nums, return the next greater number for every element. The next greater number of x is the first greater number encountered when traversing the array clockwise; return −1 if none exists.

Inputnums = [1, 2, 1]
Output[2, -1, 2]
The 1 at index 2 wraps around to index 0 and finds 2.

def next_greater_elements(nums):
    n = len(nums)
    ans = [-1] * n
    stack = []
    for i in range(2 * n):
        x = nums[i % n]
        while stack and nums[stack[-1]] < x:
            ans[stack.pop()] = x
        if i < n:
            stack.append(i)
    return ans
function nextGreaterElements(nums) {
  const n = nums.length;
  const ans = new Array(n).fill(-1);
  const stack = [];
  for (let i = 0; i < 2 * n; i++) {
    const x = nums[i % n];
    while (stack.length && nums[stack[stack.length - 1]] < x) {
      ans[stack.pop()] = x;
    }
    if (i < n) stack.push(i);
  }
  return ans;
}
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int n = nums.length;
        int[] ans = new int[n];
        Arrays.fill(ans, -1);
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < 2 * n; i++) {
            int x = nums[i % n];
            while (!stack.isEmpty() && nums[stack.peek()] < x) {
                ans[stack.pop()] = x;
            }
            if (i < n) stack.push(i);
        }
        return ans;
    }
}
vector<int> nextGreaterElements(vector<int>& nums) {
    int n = nums.size();
    vector<int> ans(n, -1);
    vector<int> stack;
    for (int i = 0; i < 2 * n; i++) {
        int x = nums[i % n];
        while (!stack.empty() && nums[stack.back()] < x) {
            ans[stack.back()] = x; stack.pop_back();
        }
        if (i < n) stack.push_back(i);
    }
    return ans;
}
Time: O(n) Space: O(n)