IntermediateAbout 25 min

    Monotonic Stack

    Read the full article on Substack

    6 min read.

    Solve "Next Greater Element" and "Daily Temperatures" problems efficiently! Visualize how maintaining a sorted stack helps find nearest larger/smaller elements in O(n).

    Think of it this way: Think of looking for a view in a city skyline. If a taller building is in front of you, it blocks your view of smaller buildings behind it. You only see the 'next greater' building.

    a20112243341556
    next >·0·1·2·3·4·5·6
    stack →0

    Scan left to right. The stack holds indices still waiting for a bigger value to their right.

    1/22

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    Next greater element

    Sequence

    Order what the algorithm does for each element, scanning left to right.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    When should you use a Monotonic Stack?

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going