Typorithm · easy

Next Greater Element

next-greater-elementmonotonic-stackdecreasing-stackmapnext-greater
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Next Greater Element

0%

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.

01

Stack stays decreasing.

02

New number resolves smaller tops.

03

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);
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Answer map

Map each value to the first larger value after it.

const nextGreater = new Map()

2. Resolve smaller

The current number is the next-greater for every smaller value on top.

while (stack.length > 0 && stack[stack.length - 1] < num) {

3. Record answer

Pop and map each resolved value to num.

nextGreater.set(stack.pop(), num)

4. Lookup with default

Values with no greater element default to -1.

nums1.map((num) => nextGreater.get(num) ?? -1)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Next Greater Element: Lesson & Practice · Typorithm | ApplyDjinn