← Monotonic Stack

Pattern Recognition Drill

#20 — Next greater element

Medium Stacks & Queues

The Problem

For each element, find the next element to its right that is larger.

What approach would you use?

Think about it before scrolling down.

Key Signals

Monotonic Stack

Maintain decreasing stack of indices. When a larger element arrives, it's the answer for all smaller stack elements. O(n).

Common Trap

Brute force nested loop is O(n²). The monotonic stack insight gives O(n) because each element is pushed/popped at most once.

← #19 #21 →