Algo-Sim › Stacks & Monotonic Stack

Next Greater Element

Easy · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

For every element, find the first element to its right that is strictly greater, or -1 if there is none.

Problem

For each element of nums, find the first element to its right that is strictly larger. Return these values in an array, using -1 where no larger element follows.

Constraints

Edge cases to test

Follow-up questions

What if the array is circular?
Loop over 2n indices with i % n, pushing only in the first pass (LC 503): O(n).
How do you answer it for a subset of the values?
Run the stack once over the full array and store answers in a map from value to next greater (LC 496).

Solution

Java

public int[] nextGreaterElement(int[] nums) {
    int n = nums.length;
    int[] result = new int[n];
    Arrays.fill(result, -1);
    Deque<Integer> stack = new ArrayDeque<>();
    for (int i = 0; i < n; i++) {
        while (!stack.isEmpty() && nums[stack.peek()] < nums[i]) {
            int idx = stack.pop();
            result[idx] = nums[i];
        }
        stack.push(i);
    }
    return result;
}

Python

def next_greater_element(nums):
    n = len(nums)
    result = [-1] * n
    stack = []
    for i in range(n):
        while stack and nums[stack[-1]] < nums[i]:
            idx = stack.pop()
            result[idx] = nums[i]
        stack.append(i)
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> nextGreaterElement(vector<int> &nums) {
        int n = int(nums.size());
        vector<int> result = vector<int>(n);
        fill(result.begin(), result.end(), -1);
        deque<int> stack = {};
        for (int i = 0; i < n; i++) {
            while (!stack.empty() && nums[stack.back()] < nums[i]) {
                int idx = stack.back();
                stack.pop_back();
                result[idx] = nums[i];
            }
            stack.push_back(i);
        }
        return result;
    }
};

More Stacks & Monotonic Stack problems