1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Monotonic Stack
45% OFFBLACK FRIDAY SALE
Sale ends in
02Days
07Hrs
36Mins
10Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Java
  5. Monotonic Stack

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

02Days
07Hrs
36Mins
10Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
    • Java + DSA
    • Full Stack Web Dev
    • AI/ML + Python
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Monotonic Stack

Overview

A Monotonic Stack is not a new data structure; it is a pattern applied to a standard Stack. 'Monotonic' means either entirely non-increasing or entirely non-decreasing.

In a Monotonic Stack, we enforce a strict rule before pushing a new element: we pop elements from the top of the stack until the stack maintains its sorted order.

This pattern is the ultimate weapon for a very specific class of array problems: finding the Next Greater Element or Next Smaller Element in O(N) time. A naive nested loop solution would take O(N^2) time, but a monotonic stack processes every element exactly twice (once pushed, once popped), resulting in strict O(N) time complexity.

Syntax

The Next Greater Element Pattern
java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class MonotonicStack {
    // Problem: For every element, find the next element to its right that is larger.
    // Example: [2, 1, 2, 4, 3] -> [4, 2, 4, -1, -1]
    
    public static int[] nextGreaterElement(int[] nums) {
        int[] result = new int[nums.length];
        Arrays.fill(result, -1); // Default if no greater element exists
        
        // Stack will store INDICES, not values, to maintain a monotonically decreasing stack
        Deque<Integer> stack = new ArrayDeque<>();
        
        for (int i = 0; i < nums.length; i++) {
            // While current element is GREATER than the element at the top of the stack...
            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
                // We found the 'Next Greater Element' for the index at the top of the stack!
                int prevIndex = stack.pop();
                result[prevIndex] = nums[i];
            }
            // Push current index onto the stack
            stack.push(i);
        }
        
        return result;
    }
}

Common Pitfalls

  • Storing values instead of indices. A very common mistake is pushing nums[i] onto the stack instead of i. If you only push values, when you find a greater element, you don't know where to put it in the result array! Always push indices.
  • Using the wrong inequality. If you want the 'Next Greater' element, use a strictly decreasing stack (nums[i] > nums[stack.peek()]). If you want the 'Next Smaller', use an increasing stack (nums[i] < nums[stack.peek()]).
  • Forgetting to handle elements left in the stack. After the loop finishes, any indices remaining in the stack have no 'Next Greater' element. You should initialize the result array with -1 (or whatever default) beforehand to handle this automatically.

Interview Questions

Why is a Monotonic Stack solution O(N) time complexity, even though it has a nested while loop inside a for loop?

Because every element is pushed onto the stack exactly once, and popped off the stack at most once. Over the course of the entire for loop, the inner while loop will only execute a maximum of N times total. Therefore, the total operations scale linearly with N, making it O(N).

How do you find the 'Previous Greater Element' instead of the 'Next Greater'?

Instead of iterating from left-to-right (0 to N-1), you iterate from right-to-left (N-1 down to 0). The stack logic remains exactly the same. When iterating backwards, finding the 'next' element in the iteration means finding the 'previous' element in the physical array.

Real-World Example

Stock Market algorithms use monotonic stacks to calculate 'Span'. If you have an array of daily stock prices, you want to know for each day how many consecutive days prior the price was lower or equal. A monotonic stack calculates this for the entire history in strict O(N) time, rather than comparing every day against every previous day (O(N^2)).

example
java
public int[] calculateStockSpans(int[] prices) {
    int[] spans = new int[prices.length];
    Deque<Integer> stack = new ArrayDeque<>(); // Stores indices
    
    for (int i = 0; i < prices.length; i++) {
        // Pop all previous days where the price was LOWER than today
        while (!stack.isEmpty() && prices[stack.peek()] <= prices[i]) {
            stack.pop();
        }
        // Span is current day minus the index of the last day that was HIGHER
        spans[i] = stack.isEmpty() ? (i + 1) : (i - stack.peek());
        stack.push(i);
    }
    return spans;
}

Check Your Knowledge

Test your understanding of Monotonic Stack with these quick questions.

Question 1

What is stored in a Monotonic Stack for the Next Greater Element problem?

Question 2

What is the time complexity of the Monotonic Stack pattern on an array of size N?

Question 3

If finding 'Next Greater Element' requires a decreasing stack, what does an increasing stack find?

Take Java Quiz
Outline
JVM ArchitectureVariablesData TypesOperatorsIf-Else StatementsSwitch StatementsLoops (For, While)Methods (Functions)Variable Scope1D Arrays2D ArraysStringsStringBuilder
Classes & ObjectsConstructorsThe this KeywordInheritanceThe super KeywordPolymorphismMethod OverloadingMethod OverridingEncapsulationAccess ModifiersAbstract ClassesInterfaces
Try-CatchThrow vs. ThrowsCustom ExceptionsArrayListHashMapHashSetWrapper ClassesAutoboxing & Unboxing
Lambda ExpressionsStreams APIThe Optional Class
Singly Linked ListDoubly Linked ListStackQueuePriority QueueHash Map InternalsCircular Linked ListMonotonic StackCircular Queue
Linear SearchBinary SearchTwo Pointers PatternBig O Space ComplexityInsertion SortMerge SortQuick SortFixed Sliding WindowVariable Sliding WindowPrefix Sum Pattern
Binary TreesBSTPrefix TreesMin-HeapMax-HeapGraph Adjacency ListGraph Adjacency Matrix
Recursion FundamentalsBacktrackingBreadth-First SearchLevel OrderTree DFSInorder TraversalPreorder TraversalPostorder TraversalGraph DFSDijkstra's AlgorithmTopological Sort1D Dynamic Programming2D Dynamic ProgrammingTop-Down (Memoization)Bottom-Up (Tabulation)Cycle DetectionMerge Intervals Pattern
Java

Monotonic Stack

Overview

A Monotonic Stack is not a new data structure; it is a pattern applied to a standard Stack. 'Monotonic' means either entirely non-increasing or entirely non-decreasing.

In a Monotonic Stack, we enforce a strict rule before pushing a new element: we pop elements from the top of the stack until the stack maintains its sorted order.

This pattern is the ultimate weapon for a very specific class of array problems: finding the Next Greater Element or Next Smaller Element in O(N) time. A naive nested loop solution would take O(N^2) time, but a monotonic stack processes every element exactly twice (once pushed, once popped), resulting in strict O(N) time complexity.

Syntax

The Next Greater Element Pattern
java
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

public class MonotonicStack {
    // Problem: For every element, find the next element to its right that is larger.
    // Example: [2, 1, 2, 4, 3] -> [4, 2, 4, -1, -1]
    
    public static int[] nextGreaterElement(int[] nums) {
        int[] result = new int[nums.length];
        Arrays.fill(result, -1); // Default if no greater element exists
        
        // Stack will store INDICES, not values, to maintain a monotonically decreasing stack
        Deque<Integer> stack = new ArrayDeque<>();
        
        for (int i = 0; i < nums.length; i++) {
            // While current element is GREATER than the element at the top of the stack...
            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
                // We found the 'Next Greater Element' for the index at the top of the stack!
                int prevIndex = stack.pop();
                result[prevIndex] = nums[i];
            }
            // Push current index onto the stack
            stack.push(i);
        }
        
        return result;
    }
}

Common Pitfalls

  • Storing values instead of indices. A very common mistake is pushing nums[i] onto the stack instead of i. If you only push values, when you find a greater element, you don't know where to put it in the result array! Always push indices.
  • Using the wrong inequality. If you want the 'Next Greater' element, use a strictly decreasing stack (nums[i] > nums[stack.peek()]). If you want the 'Next Smaller', use an increasing stack (nums[i] < nums[stack.peek()]).
  • Forgetting to handle elements left in the stack. After the loop finishes, any indices remaining in the stack have no 'Next Greater' element. You should initialize the result array with -1 (or whatever default) beforehand to handle this automatically.

Interview Questions

Why is a Monotonic Stack solution O(N) time complexity, even though it has a nested while loop inside a for loop?

Because every element is pushed onto the stack exactly once, and popped off the stack at most once. Over the course of the entire for loop, the inner while loop will only execute a maximum of N times total. Therefore, the total operations scale linearly with N, making it O(N).

How do you find the 'Previous Greater Element' instead of the 'Next Greater'?

Instead of iterating from left-to-right (0 to N-1), you iterate from right-to-left (N-1 down to 0). The stack logic remains exactly the same. When iterating backwards, finding the 'next' element in the iteration means finding the 'previous' element in the physical array.

Real-World Example

Stock Market algorithms use monotonic stacks to calculate 'Span'. If you have an array of daily stock prices, you want to know for each day how many consecutive days prior the price was lower or equal. A monotonic stack calculates this for the entire history in strict O(N) time, rather than comparing every day against every previous day (O(N^2)).

example
java
public int[] calculateStockSpans(int[] prices) {
    int[] spans = new int[prices.length];
    Deque<Integer> stack = new ArrayDeque<>(); // Stores indices
    
    for (int i = 0; i < prices.length; i++) {
        // Pop all previous days where the price was LOWER than today
        while (!stack.isEmpty() && prices[stack.peek()] <= prices[i]) {
            stack.pop();
        }
        // Span is current day minus the index of the last day that was HIGHER
        spans[i] = stack.isEmpty() ? (i + 1) : (i - stack.peek());
        stack.push(i);
    }
    return spans;
}

Check Your Knowledge

Test your understanding of Monotonic Stack with these quick questions.

Question 1

What is stored in a Monotonic Stack for the Next Greater Element problem?

Question 2

What is the time complexity of the Monotonic Stack pattern on an array of size N?

Question 3

If finding 'Next Greater Element' requires a decreasing stack, what does an increasing stack find?

Take Java Quiz

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A

Java coding notes for Indian students — 79 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in Java

  1. JVM Architecture
  2. Variables
  3. Data Types
  4. Operators
  5. If-Else Statements
  6. Switch Statements
  7. Loops (For, While)
  8. Methods (Functions)
  9. Variable Scope
  10. 1D Arrays
  11. 2D Arrays
  12. Strings
  13. StringBuilder
  14. Classes & Objects
  15. Constructors
  16. The this Keyword
  17. Inheritance
  18. The super Keyword
  19. Polymorphism
  20. Method Overloading
  21. Method Overriding
  22. Encapsulation
  23. Access Modifiers
  24. Abstract Classes
  25. Interfaces
  26. Try-Catch
  27. Throw vs. Throws
  28. Custom Exceptions
  29. ArrayList
  30. HashMap
  31. HashSet
  32. Wrapper Classes
  33. Autoboxing & Unboxing
  34. Lambda Expressions
  35. Streams API
  36. The Optional Class
  37. Singly Linked List
  38. Doubly Linked List
  39. Stack
  40. Queue
  41. Priority Queue
  42. Hash Map Internals
  43. Circular Linked List
  44. Monotonic Stack
  45. Circular Queue
  46. Linear Search
  47. Binary Search
  48. Two Pointers Pattern
  49. Big O Space Complexity
  50. Insertion Sort
  51. Merge Sort
  52. Quick Sort
  53. Fixed Sliding Window
  54. Variable Sliding Window
  55. Prefix Sum Pattern
  56. Binary Trees
  57. BST
  58. Prefix Trees
  59. Min-Heap
  60. Max-Heap
  61. Graph Adjacency List
  62. Graph Adjacency Matrix
  63. Recursion Fundamentals
  64. Backtracking
  65. Breadth-First Search
  66. Level Order
  67. Tree DFS
  68. Inorder Traversal
  69. Preorder Traversal
  70. Postorder Traversal
  71. Graph DFS
  72. Dijkstra's Algorithm
  73. Topological Sort
  74. 1D Dynamic Programming
  75. 2D Dynamic Programming
  76. Top-Down (Memoization)
  77. Bottom-Up (Tabulation)
  78. Cycle Detection
  79. Merge Intervals Pattern

Study next

  • All coding notes
  • Java notes home
  • Java certification quiz
  • Online compiler
  • Interview Q&A