Next Greater Element I — Monotonic Stack

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem

For each nums1[i], find the next greater element to its right in nums2. Return -1 if none.


Approach — Monotonic Stack on nums2

Process nums2 with a decreasing monotonic stack. When we find an element greater than stack top, that element is the NGE for the popped element. Store in hashmap.

Time: O(m+n) | Space: O(m)


Solutions

Python

class Solution:
    def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
        nge={}; stack=[]
        for n in nums2:
            while stack and stack[-1]<n:
                nge[stack.pop()]=n
            stack.append(n)
        return [nge.get(n,-1) for n in nums1]

C++

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2){
        unordered_map<int,int> nge; stack<int> st;
        for(int n:nums2){
            while(!st.empty()&&st.top()<n){nge[st.top()]=n;st.pop();}
            st.push(n);
        }
        vector<int> res;
        for(int n:nums1) res.push_back(nge.count(n)?nge[n]:-1);
        return res;
    }
};

Complexity

  • Time: O(m+n) | Space: O(m)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro