The monotonic stack is one of those algorithmic patterns that feels like magic the first time you see it. It transforms brute-force $O(N^2)$ solutions into elegant $O(N)$ linear time solutions. At its core, a monotonic stack is simply a regular stack that maintains its elements in sorted order, either strictly increasing or strictly decreasing. In this article, we will dissect this pattern, understand exactly when to apply it, and walk through real interview questions to solidify your understanding.
When to use this pattern
In coding interviews, you will often encounter problems where you need to find the "next greater" or "next smaller" element for every item in an array.
The brute-force approach is intuitive: for every element at index i, you run a nested loop starting from i + 1 to find the first element that satisfies the condition. However, this nested looping results in an $O(N^2)$ time complexity, which will result in a Time Limit Exceeded (TLE) error for arrays larger than $10^4$ elements.
You should immediately consider a monotonic stack when you see these signals in a problem statement:
- Finding the Next Greater Element (NGE) or Next Smaller Element (NSE).
- Finding the Previous Greater Element (PGE) or Previous Smaller Element (PSE).
- Problems asking for the "span" of stock prices, or the number of days until a warmer temperature.
- Geometric array problems like finding the largest rectangle in a histogram or trapping rain water.
The monotonic stack acts as a "memory" of unresolved elements. If you are looking for the next greater element, you keep elements in the stack until you find a larger element that resolves them.
The core idea
Let's trace the core idea using a simple example: finding the Next Greater Element for the array [2, 1, 4, 3].
We will iterate through the array and use a stack to keep track of elements for which we haven't found a greater element yet. To maintain a monotonic decreasing stack, we ensure that elements from the bottom to the top of the stack are in decreasing order.
- Index 0 (Value 2): The stack is empty. We push
2. Stack:[2]. - Index 1 (Value 1):
1is less than2. It doesn't resolve the next greater element for2. We push1. Stack:[2, 1]. - Index 2 (Value 4):
4is greater than1. This means4is the Next Greater Element for1! We pop1and record its answer. Now the top of the stack is2.4is also greater than2, so4is the Next Greater Element for2. We pop2and record its answer. The stack is empty. We push4. Stack:[4]. - Index 3 (Value 3):
3is less than4. We push3. Stack:[4, 3].
Elements left in the stack at the end [4, 3] do not have a next greater element, so their answer remains the default (usually -1).
Template
Here is the standard template for finding the Next Greater Element. Notice that we store indices in the stack, not the actual values. This is a crucial best practice because having the index allows us to easily place the result in the correct position in the output array, and it allows us to calculate distances (widths) if needed.
def next_greater_elements(arr):
n = len(arr)
res = [-1] * n
stack = [] # stores indices
for i in range(n):
# While stack is not empty and current element is greater than the element at stack top
while stack and arr[stack[-1]] < arr[i]:
idx = stack.pop()
res[idx] = arr[i] # Resolve the popped element
stack.append(i) # Push current index as unresolved
return resWorked examples
Let's apply this template to some classic interview problems.
Example 1: Daily Temperatures
Problem: Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the $i^{th}$ day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Approach: This is a direct application of the Next Greater Element pattern. The only difference is that instead of storing the actual warmer temperature in the result array, we need to store the distance (number of days) between the current day and the day of the warmer temperature. Because our stack stores indices, calculating the distance is simply current_index - popped_index.
Complexity:
- Time Complexity: $O(N)$ because each index is pushed and popped at most once.
- Space Complexity: $O(N)$ in the worst case (e.g., temperatures are strictly decreasing, so nothing gets popped until the end).
def dailyTemperatures(temperatures):
n = len(temperatures)
res = [0] * n
stack = []
for i in range(n):
while stack and temperatures[stack[-1]] < temperatures[i]:
idx = stack.pop()
res[idx] = i - idx # Calculate the distance
stack.append(i)
return resExample 2: Largest Rectangle in Histogram
Problem: Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
Approach: This is a notoriously difficult problem that becomes trivial once you understand the monotonic stack. For any given bar at index i, the largest rectangle that uses heights[i] as its minimum height extends to the left until it hits a shorter bar (Previous Smaller Element), and to the right until it hits a shorter bar (Next Smaller Element).
The area is heights[i] * width, where width = next_smaller_index - previous_smaller_index - 1.
We can use a strictly increasing monotonic stack to find both boundaries in a single pass!
- When we are at index
iandheights[i] < heights[stack.top()], it meansiis the Next Smaller Element for the bar atstack.top(). - When we pop
stack.top(), the new top of the stack is naturally its Previous Smaller Element!
To handle edge cases gracefully, we can append a 0 height to the end of the array to force all remaining elements in the stack to pop at the end.
Complexity:
- Time Complexity: $O(N)$ as we process each bar at most twice.
- Space Complexity: $O(N)$ for the stack.
def largestRectangleArea(heights):
heights.append(0) # Dummy bar to flush the stack
stack = [-1] # Dummy index for the left boundary of the first bar
max_area = 0
for i in range(len(heights)):
while len(stack) > 1 and heights[stack[-1]] > heights[i]:
h = heights[stack.pop()]
# The new stack top is the Previous Smaller Element
# i is the Next Smaller Element
w = i - stack[-1] - 1
max_area = max(max_area, h * w)
stack.append(i)
heights.pop() # Restore original array
return max_areaExample 3: Next Greater Element II (Circular Array)
Problem: Given a circular integer array nums (i.e., the next element of nums[nums.length - 1] is nums[0]), return the next greater number for every element in nums.
Approach: The array is circular, meaning if we don't find a greater element to the right, we can wrap around and look from the beginning of the array. The standard trick for circular arrays is to conceptually double the array. Instead of actually duplicating the array in memory, we can just run our for loop 2 * n times and use the modulo operator i % n to access the elements.
Complexity:
- Time Complexity: $O(N)$ because we iterate $2N$ times.
- Space Complexity: $O(N)$ for the stack and result array.
def nextGreaterElements(nums):
n = len(nums)
res = [-1] * n
stack = []
# Loop twice to simulate circular array
for i in range(2 * n):
curr_idx = i % n
while stack and nums[stack[-1]] < nums[curr_idx]:
idx = stack.pop()
res[idx] = nums[curr_idx]
# Only push indices from the first pass
if i < n:
stack.append(curr_idx)
return resVariations and pitfalls
While the template is robust, there are a few nuances you need to be aware of during high-pressure interviews:
- Strictly vs. Non-Strictly Monotonic: Pay close attention to whether the problem requires a strictly increasing stack (
<) or a non-decreasing stack (<=). If the problem asks for the next strictly greater element, use<in your while loop condition. If it asks for the next greater or equal element, use<=. Handling duplicates incorrectly is the number one reason candidates fail test cases on these problems. - Monotonic Stack vs. Monotonic Queue: Do not confuse this pattern with the Monotonic Queue pattern (often used with a Deque). A monotonic queue is used for Sliding Window problems (like Sliding Window Maximum) where elements naturally expire as the window moves. A monotonic stack is used when elements only expire when a specific threshold (greater/smaller) is met, regardless of window size.
Practice checklist
To truly master the monotonic stack, you need to build muscle memory. Start by implementing the standard Next Greater Element problem from scratch without looking at the template. Once you are comfortable, move on to the geometric problems like Largest Rectangle in Histogram and Trapping Rain Water.
- Trace the stack state on paper for small inputs (e.g.,
[5, 4, 3, 2, 1]vs[1, 2, 3, 4, 5]). Understanding the worst-case space complexity scenarios will help you defend your solution in an interview. - Practice modifying the template for Next Smaller Element (just flip the
<to>). - Review the Sliding Window Pattern to understand the difference between a monotonic stack and a monotonic queue.