Skip to content
DSA Visualizerpreview

Next greater element (monotonic stack)

Keep a stack of values still waiting for something bigger; each value is pushed and popped once.

O(n): each index is pushed and popped once time · O(n) space

Values4, 5, 2, 25, 7, 18

For each value in 4, 5, 2, 25, 7, 18, find the first bigger value to its right.

Input 4, 5, 2, 25, 7, 18. Answers so far: ?, ?, ?, ?, ?, ?. Stack, top first: empty.
  • compare
  • swap or write
  • settled

1 / 22

Speed

Space play · ← → step · Home End jump · drag the strip to scrub