Home Interview Mastering Monotonic Stack Interview Problems: A Complete Guide
Advanced 3 min · July 13, 2026

Mastering Monotonic Stack Interview Problems: A Complete Guide

Learn monotonic stack pattern with real interview questions, code examples, and debugging tips.

N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Drawn from code that ran under real load.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 20-25 min read
  • Basic understanding of stack data structure (push, pop, peek).
  • Familiarity with arrays and iteration.
  • Knowledge of time and space complexity analysis.
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • Monotonic stack maintains elements in increasing or decreasing order.
  • Used for problems involving next greater/smaller elements, sliding window maximum, and histogram area.
  • Time complexity is typically O(n) with O(n) space.
  • Key operations: push, pop while maintaining monotonic property.
  • Common variants: increasing stack for next smaller, decreasing for next greater.
✦ Definition~90s read
What is Monotonic Stack Interview Problems?

A monotonic stack is a stack that maintains its elements in a strictly increasing or decreasing order, used to efficiently solve problems involving next greater or smaller elements.

Imagine you're organizing a line of people by height.
Plain-English First

Imagine you're organizing a line of people by height. A monotonic stack is like a bouncer who only lets people in if they are taller (or shorter) than the last person. This helps quickly find who is the next taller person in line.

When you're in a coding interview and the interviewer asks you to find the next greater element for every element in an array, your heart might skip a beat. But what if you could solve it in O(n) time with a simple stack? That's the power of the monotonic stack pattern.

Monotonic stack is a technique where you maintain a stack that is either strictly increasing or decreasing. It's a go-to pattern for problems involving 'next greater', 'next smaller', 'previous greater', or 'previous smaller' elements. It also appears in more complex problems like 'Largest Rectangle in Histogram' and 'Trapping Rain Water'.

In this guide, we'll break down the monotonic stack pattern, walk through classic interview problems with detailed solutions, and share tips to ace your interview. By the end, you'll be able to recognize and solve monotonic stack problems with confidence.

What is a Monotonic Stack?

A monotonic stack is a stack that maintains its elements in a specific order — either strictly increasing or strictly decreasing. It's used to solve problems where you need to find the next greater or smaller element efficiently.

Types: - Increasing stack: Elements are in increasing order from bottom to top. Used for next smaller element. - Decreasing stack: Elements are in decreasing order. Used for next greater element.

How it works: You iterate through the array. For each element, you pop elements from the stack that violate the monotonic property. The popped elements' results are updated using the current element. Then you push the current element onto the stack.

Time Complexity: O(n) — each element is pushed and popped at most once. Space Complexity: O(n) — stack can hold up to n elements.

monotonic_stack_template.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
def next_greater_element(nums):
    n = len(nums)
    result = [-1] * n
    stack = []  # decreasing stack (store indices)
    for i in range(n):
        while stack and nums[stack[-1]] < nums[i]:
            idx = stack.pop()
            result[idx] = nums[i]
        stack.append(i)
    return result

# Example
print(next_greater_element([2, 1, 3, 4]))  # Output: [3, 3, 4, -1]
Output
[3, 3, 4, -1]
💡Remember the Monotonic Property
📊 Production Insight
In production, always consider edge cases like empty arrays or duplicate values. Duplicates may require strict or non-strict comparison depending on problem.
🎯 Key Takeaway
Monotonic stack reduces nested loops to linear time by maintaining a candidate list in sorted order.

Classic Problem: Next Greater Element I

Problem: Given two arrays nums1 and nums2, where nums1 is a subset of nums2, find the next greater element for each element in nums1 within nums2.

Approach: Use a monotonic decreasing stack on nums2 to precompute next greater elements for all elements. Store in a hash map. Then answer for nums1 in O(1) each.

Steps: 1. Create a hash map next_greater. 2. Iterate through nums2 with a decreasing stack. 3. For each popped element, set its next greater to current element. 4. After loop, remaining elements have no next greater (store -1). 5. Build result for nums1 using the map.

Complexities: Time O(n + m), Space O(n).

next_greater_element_i.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
def nextGreaterElement(nums1, nums2):
    stack = []
    next_greater = {}
    for num in nums2:
        while stack and stack[-1] < num:
            next_greater[stack.pop()] = num
        stack.append(num)
    for num in stack:
        next_greater[num] = -1
    return [next_greater[num] for num in nums1]

# Example
print(nextGreaterElement([4,1,2], [1,3,4,2]))  # Output: [-1,3,-1]
Output
[-1, 3, -1]
🔥Interview Tip
🎯 Key Takeaway
Precomputing next greater elements with a stack and hash map allows O(1) lookups for subset queries.

Classic Problem: Daily Temperatures

Problem: Given an array of temperatures, return an array such that answer[i] is the number of days you have to wait until a warmer temperature. If no warmer day, answer[i] = 0.

Approach: Use a decreasing stack of indices. When a warmer temperature is found, pop indices and compute the difference.

Steps: 1. Initialize result array with zeros. 2. Iterate through temperatures with index i. 3. While stack not empty and temperatures[stack[-1]] < temperatures[i]: - Pop index j. - result[j] = i - j. 4. Push i onto stack.

Complexities: Time O(n), Space O(n).

daily_temperatures.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
def dailyTemperatures(temperatures):
    n = len(temperatures)
    result = [0] * n
    stack = []
    for i in range(n):
        while stack and temperatures[stack[-1]] < temperatures[i]:
            j = stack.pop()
            result[j] = i - j
        stack.append(i)
    return result

# Example
print(dailyTemperatures([73,74,75,71,69,72,76,73]))  # Output: [1,1,4,2,1,1,0,0]
Output
[1, 1, 4, 2, 1, 1, 0, 0]
💡Edge Cases
📊 Production Insight
In real-world weather apps, this algorithm can be used to compute forecast trends efficiently.
🎯 Key Takeaway
The stack stores indices of days waiting for a warmer temperature. The difference gives the wait time.

Classic Problem: Largest Rectangle in Histogram

Problem: Given an array of bar heights, find the largest rectangle that can be formed in the histogram.

Approach: Use an increasing stack of indices. For each bar, pop bars taller than current, calculate area using current index as right boundary and the new top as left boundary.

Steps: 1. Append 0 to heights to handle remaining bars. 2. Iterate through heights with index i. 3. While stack not empty and heights[stack[-1]] > heights[i]: - Pop height h = heights[stack.pop()]. - Width = i if stack empty else i - stack[-1] - 1. - Update max area. 4. Push i.

Complexities: Time O(n), Space O(n).

largest_rectangle_histogram.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def largestRectangleArea(heights):
    stack = []
    max_area = 0
    heights.append(0)  # sentinel
    for i, h in enumerate(heights):
        while stack and heights[stack[-1]] > h:
            height = heights[stack.pop()]
            width = i if not stack else i - stack[-1] - 1
            max_area = max(max_area, height * width)
        stack.append(i)
    heights.pop()
    return max_area

# Example
print(largestRectangleArea([2,1,5,6,2,3]))  # Output: 10
Output
10
⚠ Sentinel Value
📊 Production Insight
This algorithm is used in image processing for detecting maximum white rectangles in binary images.
🎯 Key Takeaway
The stack maintains increasing heights. When a smaller height appears, it triggers area calculation for taller bars.

Classic Problem: Trapping Rain Water

Problem: Given an array of non-negative integers representing elevation, compute how much water can be trapped after rain.

Approach: Use a decreasing stack. When a bar taller than the top is found, pop the top as a valley, and calculate water trapped using the new top as left boundary and current as right boundary.

Steps: 1. Initialize stack and water = 0. 2. Iterate through heights with index i. 3. While stack not empty and heights[stack[-1]] < heights[i]: - Pop top = stack.pop(). - If stack empty, break. - Distance = i - stack[-1] - 1. - Bounded height = min(heights[stack[-1]], heights[i]) - heights[top]. - Water += distance * bounded height. 4. Push i.

Complexities: Time O(n), Space O(n).

trapping_rain_water.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def trap(height):
    stack = []
    water = 0
    for i, h in enumerate(height):
        while stack and height[stack[-1]] < h:
            top = stack.pop()
            if not stack:
                break
            distance = i - stack[-1] - 1
            bounded_height = min(height[stack[-1]], h) - height[top]
            water += distance * bounded_height
        stack.append(i)
    return water

# Example
print(trap([0,1,0,2,1,0,1,3,2,1,2,1]))  # Output: 6
Output
6
🔥Alternative Approaches
📊 Production Insight
This algorithm is used in flood modeling and geographic information systems.
🎯 Key Takeaway
Water is trapped between two taller bars. The stack helps find the left and right boundaries for each valley.

Advanced Problem: Sum of Subarray Minimums

Problem: Given an array, find the sum of minimums of all contiguous subarrays. Return result modulo 10^9+7.

Approach: For each element, find how many subarrays it is the minimum of. Use two passes with monotonic stack: one for previous smaller element (PSE) and one for next smaller element (NSE).

Steps: 1. Compute left[i] = distance to previous smaller element (strictly smaller). 2. Compute right[i] = distance to next smaller element (strictly smaller). 3. For each i, contribution = arr[i] left[i] right[i]. 4. Sum all contributions modulo MOD.

Complexities: Time O(n), Space O(n).

sum_subarray_minimums.pyPYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
def sumSubarrayMins(arr):
    MOD = 10**9 + 7
    n = len(arr)
    left = [0] * n
    right = [0] * n
    stack = []
    # Previous smaller
    for i in range(n):
        while stack and arr[stack[-1]] >= arr[i]:
            stack.pop()
        left[i] = i - stack[-1] if stack else i + 1
        stack.append(i)
    stack.clear()
    # Next smaller
    for i in range(n-1, -1, -1):
        while stack and arr[stack[-1]] > arr[i]:
            stack.pop()
        right[i] = stack[-1] - i if stack else n - i
        stack.append(i)
    result = 0
    for i in range(n):
        result = (result + arr[i] * left[i] * right[i]) % MOD
    return result

# Example
print(sumSubarrayMins([3,1,2,4]))  # Output: 17
Output
17
💡Handling Duplicates
📊 Production Insight
This technique is used in data analysis to compute rolling statistics efficiently.
🎯 Key Takeaway
Each element contributes to subarrays where it is the minimum. The product of distances to smaller elements gives the count.

Interview Tips and Variations

Recognizing the Pattern: - Problem asks for 'next greater/smaller', 'previous greater/smaller', or 'nearest greater/smaller'. - Problem involves calculating something based on the nearest larger or smaller element. - Examples: Stock span, sliding window maximum (can use deque), maximum of minimums of every window size.

Common Variations: - Next Greater Element II (circular array): iterate twice. - Online Stock Span: maintain stack of (price, span). - Maximum Width Ramp: use decreasing stack of indices.

Interview Communication: 1. Start with brute force O(n²) and explain why it's suboptimal. 2. Introduce monotonic stack as optimization. 3. Walk through an example with a small array. 4. Discuss edge cases: empty, duplicates, decreasing/increasing order. 5. Analyze time and space complexity.

Common Mistakes: - Using wrong monotonic property (increasing vs decreasing). - Forgetting to handle remaining elements in stack. - Off-by-one errors in width calculations.

⚠ Practice Makes Perfect
📊 Production Insight
In production, always test with edge cases like all equal elements, single element, and large inputs to ensure O(n) performance.
🎯 Key Takeaway
Monotonic stack is a versatile pattern. Master it by understanding the underlying monotonic property and practicing variations.
● Production incidentPOST-MORTEMseverity: high

The Slow Stock Price Tracker

Symptom
Users experienced app freezing and timeouts when viewing stock price spans.
Assumption
The developer assumed the brute-force approach was acceptable for small datasets.
Root cause
The stock span calculation used nested loops, leading to O(n²) time complexity for large arrays.
Fix
Replaced with a monotonic decreasing stack, reducing complexity to O(n).
Key lesson
  • Always consider worst-case input size.
  • Monotonic stack can optimize many 'next greater' style problems.
  • Profile your code with realistic data volumes.
  • Use appropriate data structures to avoid quadratic time.
  • Document assumptions about input constraints.
Production debug guideSymptom to Action3 entries
Symptom · 01
Unexpected results for next greater element (e.g., wrong indices).
Fix
Check if stack maintains strictly increasing/decreasing order. Verify comparison operator (>= vs >).
Symptom · 02
Stack overflow or excessive memory usage.
Fix
Ensure stack size is bounded by input size. Use iterative approach, not recursion.
Symptom · 03
Timeouts on large inputs.
Fix
Verify O(n) complexity. Look for hidden nested loops inside while condition.
★ Quick Debug Cheat SheetCommon issues and fixes for monotonic stack implementations.
Wrong next greater element (e.g., returns smaller element).
Immediate action
Check monotonic property: decreasing stack for next greater.
Commands
Print stack after each push/pop.
Verify comparison: while stack and arr[stack[-1]] < arr[i].
Fix now
Ensure you pop when current element is greater than top of stack.
Off-by-one errors in indices.+
Immediate action
Check if you're storing indices or values.
Commands
Print result array after each iteration.
Verify initialization (e.g., -1 for no greater element).
Fix now
Initialize result with -1 or 0 as appropriate.
Stack not empty after loop.+
Immediate action
Process remaining elements in stack.
Commands
After loop, while stack: pop and set result.
Check if remaining elements have no greater element.
Fix now
Set result for remaining indices to -1 (or default).
ProblemStack TypeTime ComplexitySpace Complexity
Next Greater ElementDecreasingO(n)O(n)
Daily TemperaturesDecreasingO(n)O(n)
Largest Rectangle in HistogramIncreasingO(n)O(n)
Trapping Rain WaterDecreasingO(n)O(n)
Sum of Subarray MinimumsIncreasing (two passes)O(n)O(n)
⚙ Quick Reference
6 commands from this guide
FileCommand / CodePurpose
monotonic_stack_template.pydef next_greater_element(nums):What is a Monotonic Stack?
next_greater_element_i.pydef nextGreaterElement(nums1, nums2):Classic Problem
daily_temperatures.pydef dailyTemperatures(temperatures):Classic Problem
largest_rectangle_histogram.pydef largestRectangleArea(heights):Classic Problem
trapping_rain_water.pydef trap(height):Classic Problem
sum_subarray_minimums.pydef sumSubarrayMins(arr):Advanced Problem

Key takeaways

1
Monotonic stack is a powerful pattern for O(n) solutions to problems involving nearest larger/smaller elements.
2
Always identify the monotonic property needed
decreasing for next greater, increasing for next smaller.
3
Practice with classic problems
Next Greater Element, Daily Temperatures, Largest Rectangle in Histogram, Trapping Rain Water, Sum of Subarray Minimums.
4
Handle edge cases
empty arrays, duplicates, circular arrays, and remaining stack elements.

Common mistakes to avoid

3 patterns
×

Using wrong monotonic property (e.g., increasing stack for next greater).

×

Forgetting to process remaining elements in stack after loop.

×

Off-by-one errors in width calculations for histogram and rain water.

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
Implement a function to find the next greater element for each element i...
Q02SENIOR
Given an array of integers, find the largest rectangle area in a histogr...
Q03SENIOR
Given an array, find the sum of minimums of all contiguous subarrays mod...
Q01 of 03JUNIOR

Implement a function to find the next greater element for each element in an array. If no greater element, return -1.

ANSWER
Use a decreasing stack. Iterate through array, pop while top < current, set result for popped index to current. Push current. After loop, remaining indices get -1.
FAQ · 3 QUESTIONS

Frequently Asked Questions

01
What is the difference between monotonic stack and monotonic queue?
02
Can monotonic stack be used for circular arrays?
03
How do I handle duplicates in monotonic stack problems?
N
Naren Founder & Principal Engineer

20+ years shipping production code across the stack, with years spent interviewing engineers. Drawn from code that ran under real load.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's Coding Patterns. Mark it forged?

3 min read · try the examples if you haven't

Previous
Best Coding Challenges for Beginners: Top Platforms and Problems to Start With
18 / 26 · Coding Patterns
Next
Interval and Range Interview Problems