LeetCopilot Logo
LeetCopilot
Home/Learning Tools/Monotonic Stack Visualizer

Monotonic Stack & Queue Visualizer

Interactive tool to master monotonic stack and queue algorithms for coding interviews. Visualize Next Greater Element, Daily Temperatures, and Sliding Window Maximum step-by-step to understand the O(N) optimization.

Next Greater Element

Step 1 / 0
Ready
Input Array
20
11
22
43
34
Monotonic Stack
Stores Indices
Result Array

Current State

💡 Looking for values > stack top
Python Solution
def next_greater_element(nums):
    n = len(nums)
    result = [-1] * n
    stack = []  # Stores indices
    
    for i in range(n):
        while stack and nums[i] > nums[stack[-1]]:
            idx = stack.pop()
            result[idx] = nums[i]
        stack.append(i)
    
    return result

Understanding Monotonic Stack & Queue

Monotonic stacks and queues are powerful techniques that solve specific range-query problems in O(N) time, down from O(N²) brute force. The core idea is to maintain elements in a specific order (increasing or decreasing) to efficiently find the "next greater" or "next smaller" element, or the maximum in a sliding window.

Three Core Patterns

Monotonic Stack

Maintains increasing or decreasing order. Used for finding next/previous greater/smaller elements (e.g., Next Greater Element).

Stack with Indices

Stores indices instead of values to calculate distances. Essential for problems like Daily Temperatures and Stock Span.

Monotonic Queue (Deque)

Supports adding/removing from both ends to maintain a sliding window maximum or minimum in O(N) time.

Key Insight

The magic of monotonic stacks is that each element is pushed onto the stack exactly once and popped at most once. This amortized analysis guarantees linear O(N) time complexity, regardless of the input distribution.

How to Use the Visualizer

  • Select a pattern type (Next Greater, Daily Temps, Sliding Window)
  • Use Next/Previous buttons to step through the algorithm
  • Watch how the stack/deque grows and shrinks to maintain order
  • Observe the resulting array being filled as relations are found
  • Use Auto Play to see the flow of data

Practice Problems

Apply what you've learned with these classic LeetCode problems:

•
Next Greater Element II (LC 503) - Circular array variant
•
Daily Temperatures (LC 739) - Distance calculation
•
•

Learn More

Dive deeper into our complete guides for Monotonic Stack & Queue:

Want to Practice LeetCode Smarter?

LeetCopilot is a free browser extension that enhances your LeetCode practice with AI-powered hints, personalized study notes, and realistic mock interviews — all designed to accelerate your coding interview preparation.

Also compatible with Edge, Brave, and Opera