easyStackStack

Next Greater Element I

easyTime: 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.

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.

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