Question Bank

Monotonic Stack Patterns

Difficulty: Medium

Five prompts on monotonic stacks for next-greater-element, daily temperatures, and largest rectangle. Mostly implementation with one trace and one bug hunt.

Question Bank
/

Monotonic Stack Patterns

Monotonic Stack Patterns

Five prompts on monotonic stacks for next-greater-element, daily temperatures, and largest rectangle. Mostly implementation with one trace and one bug hunt.

Question Bank
Medium
JavaScript
5 questions
monotonic-stack
stack
algorithms
interview-prep

811 views

23

Implement nextGreaterElement(nums) returning an array where out[i] is the next strictly greater value to the right of nums[i], or -1 if none. Aim for O(n).

Examples

Example 1:

Input: nums = [2, 1, 2, 4, 3]
Output: [4, 2, 4, -1, -1]
Explanation: Walk left to right with a stack of indices. For each new value, pop indices whose values are strictly smaller; they have just found their next-greater (current value). Push the current index. The remaining stack at the end gets -1.