1. Answer map
Map each value to the first larger value after it.
const nextGreater = new Map()Typorithm · easy
Step 1 of 8 · intro card
Monotonic Stack
Keep a decreasing stack; each new number resolves every smaller value below it, recorded in a map for lookup.
Scan nums2 keeping a stack of values still waiting for a larger one to appear.
When a new number is bigger than the stack top, it is that value's next-greater element, so pop and record it.
Finally map each query in nums1 through the answer map, defaulting to -1.
Stack stays decreasing.
New number resolves smaller tops.
Map answers, default to -1.
function nextGreaterElement(nums1, nums2) {
const nextGreater = new Map();
const stack = [];
for (const num of nums2) {
while (stack.length > 0 && stack[stack.length - 1] < num) {
nextGreater.set(stack.pop(), num);
}
stack.push(num);
}
return nums1.map((num) => nextGreater.get(num) ?? -1);
}Connect each part of the code to the concept before you type.
Map each value to the first larger value after it.
const nextGreater = new Map()The current number is the next-greater for every smaller value on top.
while (stack.length > 0 && stack[stack.length - 1] < num) {Pop and map each resolved value to num.
nextGreater.set(stack.pop(), num)Values with no greater element default to -1.
nums1.map((num) => nextGreater.get(num) ?? -1)Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.