Skip to content

503. Next Greater Element II 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<int> nextGreaterElements(vector<int>& nums) {
    const int n = nums.size();
    vector<int> ans(n, -1);
    stack<int> stack;  // a decreasing stack storing indices

    for (int i = 0; i < n * 2; ++i) {
      const int num = nums[i % n];
      while (!stack.empty() && nums[stack.top()] < num)
        ans[stack.top()] = num, stack.pop();
      if (i < n)
        stack.push(i);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] nextGreaterElements(int[] nums) {
    final int n = nums.length;
    int[] ans = new int[n];
    Arrays.fill(ans, -1);
    Deque<Integer> stack = new ArrayDeque<>(); // a decreasing stack storing indices

    for (int i = 0; i < n * 2; ++i) {
      final int num = nums[i % n];
      while (!stack.isEmpty() && nums[stack.peek()] < num)
        ans[stack.pop()] = num;
      if (i < n)
        stack.push(i);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def nextGreaterElements(self, nums: list[int]) -> list[int]:
    n = len(nums)
    ans = [-1] * n
    stack = []  # a decreasing stack storing indices

    for i in range(n * 2):
      num = nums[i % n]
      while stack and nums[stack[-1]] < num:
        ans[stack.pop()] = num
      if i < n:
        stack.append(i)

    return ans