Next Greater Element I
Difficulty: Easy · Pattern: Stack & Monotonic Stack · LeetCode #496
nums1 is a subset of nums2 (distinct values). For each x in nums1, find the first element to the right of x in nums2 that is greater than x, or −1 if none.
Examples
text
nums1 = [4, 1, 2], nums2 = [1, 3, 4, 2] → [−1, 3, −1]
nums1 = [2, 4], nums2 = [1, 2, 3, 4] → [3, −1]Hints
- Compute the next greater element for every value of nums2 once, with a monotonic stack.
- Then answer each nums1 query with a map lookup.
Approach
Traverse nums2 with a decreasing stack: when x is greater than the top, the top's next-greater is x, so pop and record it in a map. Push x. Values left on the stack have no next greater (−1). Then map nums1 through the dictionary. O(n + m).
Complexity
Time: O(n + m). Space: O(n).
Python solution
def nextGreaterElement(nums1, nums2):
nxt, st = {}, []
for x in nums2:
while st and st[-1] < x:
nxt[st.pop()] = x
st.append(x)
return [nxt.get(x, -1) for x in nums1]JavaScript solution
function nextGreaterElement(nums1, nums2) {
const nxt = new Map(), st = [];
for (const x of nums2) { while (st.length && st[st.length - 1] < x) nxt.set(st.pop(), x); st.push(x); }
return nums1.map((x) => (nxt.has(x) ? nxt.get(x) : -1));
}