Problem Statement

Next Greater Element I

Imagine you are standing in a line of people, each holding a number. For your number, the "next greater element" is the first person to your right who is holding a bigger number than you. If nobody to your right is bigger, the answer is -1. In this problem you get two arrays. nums2 is the full line of people, and nums1 is a smaller handful of those same numbers. For each number in nums1, you have to find its next greater element inside nums2.

easyStackStackTime: O(n + m) · Space: O(n)

Signals to notice

for each element in one array, find the next larger element in another arraynext greater to the rightmonotonic relationship

Brute force first

For each element in nums1, find it in nums2, then scan right for a larger one. The waste is re-scanning the same portion of nums2 for elements that share the same 'next greater.'. That direct path helps you understand the question, but it tends to treat every possibility as brand new instead of learning from earlier steps.

The key insight

Process nums2 right-to-left (or left-to-right with a stack): build a map of each element to its next greater element. A monotonic decreasing stack naturally identifies the next greater element for each value in. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Trace it on nums1=[4,1,2], nums2=[1,3,4,2]

init: stack=[], next_greater={}
num=1: stack empty, no pops; push -> stack=[1]
num=3: 1<3 pop -> next_greater{1:3}; push -> stack=[3]
num=4: 3<4 pop -> next_greater{1:3, 3:4}; push -> stack=[4]
num=2: 4>2 no pop; push -> stack=[4,2]
drain stack: pop 2 -> {2:-1}, pop 4 -> {4:-1}; map={1:3,3:4,2:-1,4:-1}
map nums1=[4,1,2] -> return [-1, 3, -1]

What must stay true

The stack holds elements that haven't yet found their next greater element, in decreasing order. When a new element is larger than the stack top, it's the 'next greater' for everything it displaces. As long as that statement keeps holding, you can trust the steps built on top of it.

Shape of the loop

stack = []; nextGreater = {}
for num in nums2:
    while stack and stack.top < num:
        nextGreater[stack.pop()] = num   # num is the next greater
    stack.push(num)
for leftover in stack: nextGreater[leftover] = -1
return [nextGreater[n] for n in nums1]

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Trying to solve it per-query from nums1 instead of precomputing the answer for all of nums2 first. The map-based approach answers every query in after one pass. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Stack Pattern