Skip to content
Preptima
mediumCodingConceptMidSenior

For each element of an array, find the first element to its right that is larger. State the invariant your stack maintains.

4 min readUpdated 2026-08-15

Answer

Short answer

Scan left to right holding a stack of indices whose answers are still unknown, kept strictly decreasing by value. Each new element resolves and pops everything smaller than it, then pushes itself.

Was this answer helpful?

Likely follow-ups

  • Change it to the next greater-or-equal element. Which character moves?
  • Now the array is circular. How do you adapt the same scan?
  • Largest rectangle in a histogram uses this technique. What is the invariant there, and why the sentinel?
  • Could you scan right to left instead, and what would the stack hold then?

Related questions

Further reading