Introduction
Welcome to your fourth lesson in the "Advanced Algorithm Patterns" module. In our last session, we mastered binary search on the answer space, a powerful technique for solving optimization problems like "minimize the maximum." We saw how framing a problem around a monotonic condition allows for highly efficient logarithmic-time solutions.
Today, we're adding another specialized pattern to your arsenal: monotonic stacks and queues. These data structures are the key to unlocking linear-time, , solutions for a class of problems that might otherwise seem to require a quadratic, , approach. These problems often involve finding the "next greater element," "previous smaller element," or calculating extremes within a sliding window.
Your goal is to understand the core principle of maintaining a monotonic (strictly increasing or decreasing) order within a stack or a double-ended queue (deque). You'll learn how this property allows us to efficiently discard irrelevant information and find solutions for problems like "Next Greater Element" and "Sliding Window Maximum."
The Monotonic Stack Pattern
Let's start with the simpler of the two structures. A monotonic stack is a regular stack with one additional rule: the elements within it are always kept in a sorted order. This simple constraint is surprisingly powerful.
To get a concise overview of what a monotonic stack is and the types of problems it solves, please watch the beginning of this video.
Monotonic Stack in 6 minutes | LeetCode Pattern
This video from AlgoMasterIO provides a quick and clear definition of monotonic stacks and the generic template for using them.
Watch from 00:00 to 01:39. Focus on: The difference between a monotonic increasing and decreasing stack. The types of problems each is suited for (e.g., next greater element vs. next smaller element). The generic three-step code template for processing array elements.
Core Application: Next Greater Element
The canonical problem for monotonic stacks is finding the "Next Greater Element" (NGE). Given an array, for each element, we want to find the first element to its right that is larger.
A brute-force solution would use nested loops, taking time. The monotonic stack gets this down to .
Let's use an intuitive analogy. Imagine the array elements are people of different heights standing in a line. To find the next taller person for someone, you look to their right. Anyone shorter than them is blocked from your view. The first person you can see is the next greater element.

How do we implement this? We iterate through the array and use a stack to keep track of elements for which we haven't yet found a NGE. We'll use a monotonic decreasing stack.
This article by Labuladong provides a fantastic analogy and a clean code template for the Next Greater Element problem. We'll focus on the reverse iteration approach, which is a very common way to implement this.
Read the first section, 'Monotonic Stack Template'. Pay close attention to: The 'people standing in a line' analogy. The logic of the while loop: why are we popping smaller elements from the stack? The linear time complexity analysis: why is it O(N) and not O(N^2)?
The logic when processing nums[i] (iterating from right to left) is:
- While the stack is not empty and
stack.top() <= nums[i]: Pop from the stack. These popped elements are "blocked" bynums[i]and cannot be the NGE for any elements to the left ofi. - Set the answer: After the loop, if the stack is empty, there is no NGE for
nums[i]. Otherwise, the NGE fornums[i]is the element now at the top of the stack. - Push: Push
nums[i]onto the stack. This maintains the decreasing order and makesnums[i]a candidate for elements further to the left.
Since each element is pushed and popped at most once, the total time complexity is .
Variation: Storing Indices
In many problems, you don't need the value of the next greater element, but rather the distance to it. For this, you store indices in the stack instead of values.
A classic example is Daily Temperatures (LeetCode 739), which asks for the number of days to wait for a warmer temperature. This is just the NGE problem reframed.
Monotonic Stack in 6 minutes | LeetCode Pattern
Let's return to the AlgoMasterIO video to see how the NGE pattern is adapted for 'Daily Temperatures'.
Watch from 04:31 to 06:08. Notice how the logic is identical to NGE, but by storing indices, we can calculate the difference (popped_index - current_index) to get the number of days.
This small change—storing indices—is a key insight that unlocks solutions to a wide variety of related problems.
The Monotonic Queue (Deque) Pattern
What happens when we care about a specific sub-region of the array, like a sliding window? A stack's LIFO (Last-In, First-Out) nature is limiting. We can add to the "right" (top) and remove from the "right" (top), but we can't efficiently remove elements that expire from the "left" end of our window.
This is where the monotonic deque (double-ended queue) comes in. It allows us to efficiently add to the back and remove from both the front and the back.
Core Application: Sliding Window Maximum (LeetCode 239)
This is a hard-level LeetCode problem and a frequent guest in senior-level interviews. Given an array and a window size k, find the maximum value in each sliding window.
- Brute force:
- Using a max-heap:
- Using a monotonic deque:
The following guide is an excellent, in-depth resource for this problem. It covers everything from the basic concept to Staff-level talking points.
LC239: Sliding Window Maximum Solution Guide
This guide by Sanjay Patidar is a complete walkthrough of the Sliding Window Maximum problem. It's tailored for interview preparation and provides the level of depth you're looking for.
First, read the sections 'Understanding the Sliding Window and Monotonic Deque Concept' and the 'ASCII Visualization of Sliding Window and Monotonic Deque'. This will establish the core algorithm.

The algorithm for maintaining the monotonic decreasing deque of indices is as follows, for each element nums[i]:
- Clean the front: Remove indices from the front of the deque that are no longer in the window (i.e.,
deque.front() <= i - k). - Clean the back: While the deque is not empty and the value at the back of the deque is smaller than
nums[i](nums[deque.back()] < nums[i]), pop from the back. Why? These smaller elements can never be the maximum in any window that also contains the largernums[i]. - Add to back: Add the current index
ito the back. - Record the maximum: Once the window is full (
i >= k - 1), the maximum for the current window isnums[deque.front()].
This process ensures the deque only contains indices of "useful" candidates for the maximum, and the best candidate is always at the front, ready for access.
Staff-Level Depth: Justification and Trade-offs
For a Staff-level interview, simply providing the optimal solution isn't enough. You need to articulate why it's optimal, discuss trade-offs, and handle edge cases with precision.
Let's continue with the same guide to explore these deeper aspects.
LC239: Sliding Window Maximum Solution Guide
Now, let's focus on the sections of the guide that prepare you for an interview discussion.
Please read the following three sections: 'Time & Space Complexity': Understand the comparison between brute-force, heap, and deque solutions. 'Interview Script & What to Say': This provides an excellent template for structuring your verbal explanation during an interview. 'FAQs': This section directly addresses the common follow-up questions you might get, like 'Why use a deque over a max-heap?' and 'How do you handle duplicates?'.
Here is a Go implementation of the solution, which you can use as a reference. Notice how it directly implements the logic we've discussed.
func maxSlidingWindow(nums []int, k int) []int {
if len(nums) == 0 || k == 0 {
return []int{}
}
// The result slice will have n - k + 1 elements.
result := make([]int, 0, len(nums)-k+1)
// The deque will store indices of the numbers in nums.
deque := []int{}
for i, num := range nums {
// 1. Clean the front: Remove indices that are out of the current window.
// The window is [i-k+1, i]. If the front index is i-k, it's one step
// outside the left boundary of the window that will form at index i.
if len(deque) > 0 && deque[0] == i-k {
deque = deque[1:]
}
// 2. Clean the back: Maintain the monotonic decreasing property.
// Remove indices of elements that are smaller than the current element.
for len(deque) > 0 && nums[deque[len(deque)-1]] < num {
deque = deque[:len(deque)-1]
}
// 3. Add to back: Add the current index to the deque.
deque = append(deque, i)
// 4. Record the maximum: Once the first full window is formed,
// start recording the maximums. The max is always at the front.
if i >= k-1 {
result = append(result, nums[deque[0]])
}
}
return result
}
Conclusion
You've now explored the monotonic stack and queue patterns, two powerful tools for solving specific types of array problems in optimal linear time. They may seem niche, but they appear frequently enough in interviews that recognizing them is a significant advantage.
Key Takeaways:
- Monotonic Stack: The go-to pattern for "next/previous greater/smaller element" problems. It operates on a LIFO basis and is typically implemented with a single pass over the array.
- Monotonic Queue (Deque): The solution for "sliding window min/max" problems. It requires efficient access to both ends: one for adding new elements and one for expiring old ones.
- Core Principle: Both structures work by maintaining a sorted order of candidate elements (or their indices), allowing for the quick discarding of elements that are no longer relevant.
- Complexity: They achieve an amortized time cost per operation, leading to an overall time complexity for a single pass through an array of size
N. - Staff-Level Articulation: Be ready to compare the deque approach to less optimal solutions (like max-heap), explain the amortized time complexity, and justify design choices like storing indices instead of values.
In our next lesson, we will cover the interval merging pattern. This is fundamental for problems involving overlapping ranges, such as scheduling conflicts or geometric intersections, which are common in system design-adjacent algorithm questions.