Next Greater Element I

For each element in nums1, find its next greater element in nums2 using a monotonic stack.

Easy
Time O(N + M) Space O(N)
LeetCode
3 min read
hash-map monotonic-stack

Problem#

nums1 is a subset of nums2. For each nums1[i], find the next greater element to its right in nums2, or -1 if none.

Examples#

  • nums1 = [4,1,2], nums2 = [1,3,4,2][-1,3,-1].
  • nums1 = [2,4], nums2 = [1,2,3,4][3,-1].

Constraints#

  • 1 <= nums1.length <= nums2.length <= 1000. All elements in nums2 are unique.

Hints#

Hint
Precompute next-greater for every nums2 value with a single monotonic stack pass.

Approach#

Right-to-left scan nums2 keeping a stack of values seen so far. For each v, pop everything <= v; the top (if any) is the next greater. Store nextGreater[v] in a hash map. Then answer each nums1[i] in O(1).

Solution#

Next Greater Element I
class Solution {
public:
vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) {
unordered_map<int,int> nxt;
stack<int> st;
for (int i = (int)nums2.size() - 1; i >= 0; --i) {
while (!st.empty() && st.top() <= nums2[i]) st.pop();
nxt[nums2[i]] = st.empty() ? -1 : st.top();
st.push(nums2[i]);
}
vector<int> ans;
ans.reserve(nums1.size());
for (int v : nums1) ans.push_back(nxt[v]);
return ans;
}
};

Editorial#

A right-to-left monotonic decreasing stack answers “next greater to the right” in O(N) total. The hash map then bridges from the second array’s positions to the first array’s queries. Without the precompute, you’d be doing O(N * M) nested searches.

Complexity#

  • Time: O(N + M).
  • Space: O(N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.