Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Stack

Monotonic Stack


max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
A monotonic stack is a special type of stack in which all elements on the stack are sorted in either descending or ascending order. The ordering can be strict (no duplicates allowed) or non-strict (duplicates allowed), which variant you use depends on the problem. In most problems, including the ones below, a non-strict monotonic stack works. It is used to solve problems that require finding the next greater or next smaller element in an array.
73727268stack
A monotonically decreasing stack (non-strict i.e. duplicates like 72 are allowed)

Problem: Next Greater Element

DESCRIPTION
Given an array of integers, find the next greater element for each element in the array. The next greater element of an element x is the first element to the right of x that is greater than x. If there is no such element, then the next greater element is -1.
Example Input: [2, 1, 3, 2, 4, 3] Output: [3, 3, 4, 4, -1, -1]
The solution iterates over each index in the input array. For each index, it checks if the element at that index is the next greater element for any previous elements in the array. In order to perform that check efficiently, we'll use a monotonic decreasing stack.
Initialization
We start by initializing our stack and our results array, with each value in the results array initialized to -1. Our stack stores the indexes of the elements in the input array that have not yet found their next greater element.
Visualization
Python
Language
def nextGreaterElement(nums):
n = len(nums)
result = [-1] * n
stack = []
for i in range(n):
while stack and nums[i] > nums[stack[-1]]:
index = stack.pop()
result[index] = nums[i]
stack.append(i)
return result
213243012345

0 / 1

Iteration
We then iterate over the input array. To check if the current element nums[i] is the next greater element for any of the previous elements in the array, we compare the current element with the element at the index at the top of the stack nums[stack[-1]].
If the stack is empty, or if nums[i] is less than nums[stack[-1]], we push the current index onto the stack.
Visualization
Python
Language
def nextGreaterElement(nums):
n = len(nums)
result = [-1] * n
stack = []
for i in range(n):
while stack and nums[i] > nums[stack[-1]]:
index = stack.pop()
result[index] = nums[i]
stack.append(i)
return result
213243012345-1-1-1-1-1-1resultstack

0 / 4

Pushing indexes 0 and 1 onto the stack
Recall that the stack contains the indexes of the elements in the input array that have not yet found their next greater element. At this point, we can see that the values at each of the indexes on the stack (i.e. nums[0] and nums[1]) are monotonically decreasing. This property allows us to check if nums[i] is the next greater element for any of the indexes on the stack efficiently.
If nums[i] is smaller than nums[stack[-1]], because the stack is monotonically decreasing, we also know that nums[i] is not the next greater element for any of the other indexes on the stack as well, so we can push index i onto the stack.
Processing Next Greater Elements
If the nums[i] is greater than nums[stack[-1]], then we have found the next greater element for the index stack[-1]. So we pop that index from the stack (idx), and update results[idx] to be nums[i].
Because it is still possible for nums[i] to be the next greatest element for the remaining indexes on the stack, we have to repeat this processing operation until nums[i] is not greater than nums[stack[-1]], at which point we have finished processing all the indexes for which nums[i] is the next greatest element, so we push i onto the stack.
Visualization
Python
Language
def nextGreaterElement(nums):
n = len(nums)
result = [-1] * n
stack = []
for i in range(n):
while stack and nums[i] > nums[stack[-1]]:
index = stack.pop()
result[index] = nums[i]
stack.append(i)
return result
213243012345i-1-1-1-1-1-1result01stack

0 / 4

Processing indexes for which 3 is the next greatest element
Popping all the elements that are smaller than nums[i] from the stack before pushing i ensures that the stack stays monotonically decreasing.
This process continues until the end of the input array, at which point the results array contains the next greater element for each element in the input array, or -1 if there is no such element.

Solution

Visualization
Python
Language
Try these examples:
def nextGreaterElement(nums):
n = len(nums)
result = [-1] * n
stack = []
for i in range(n):
while stack and nums[i] > nums[stack[-1]]:
index = stack.pop()
result[index] = nums[i]
stack.append(i)
return result
213243012345

0 / 18

Next Smaller Element

Following the same pattern, we can use a monotonically increasing stack to solve problems that require finding the next smaller element in an array.
Visualization
Python
Language
Try these examples:
def nextSmallerElement(nums):
n = len(nums)
result = [-1] * n
stack = []
for i in range(n):
while stack and nums[i] < nums[stack[-1]]:
index = stack.pop()
result[index] = nums[i]
stack.append(i)
return result
213243012345

0 / 17

Practice Problems

For more practice with problems that use a monotonic stack, try:
Daily Temperatures Leetcode | Solution
Largest Rectangle in Histogram Leetcode | Solution
Buildings with an Ocean View Leetcode

Mark as read

Next: Daily Temperatures

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Problem: Next Greater Element

Practice Problems

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress