mirror of
https://github.com/prdlk/leetcode.git
synced 2026-11-02 13:12:44 +00:00
37 lines
1.6 KiB
Plaintext
37 lines
1.6 KiB
Plaintext
---
|
|
title: Monotonic Stack
|
|
description: 'A stack keeps its items in sorted order, which finds the next larger or smaller item in one pass.'
|
|
hidden: true
|
|
---
|
|
|
|
|
|
<YouTube id="Dq_ObZwTY_Q" title="Monotonic Stack" />
|
|
|
|
A monotonic stack keeps its values in sorted order as you push elements. The order can be increasing or decreasing, depending on the problem.
|
|
|
|
A decreasing monotonic stack is the most common version. Before pushing a new value `x`, we pop from the top while the top is smaller than or equal to `x`. After those pops, pushing `x` keeps the stack decreasing from bottom to top.
|
|
|
|
This push rule is the whole idea. A monotonic deque uses the same rule, but a deque also lets you remove old elements from the front, which is useful for sliding window problems.
|
|
|
|
## Example Implementation
|
|
|
|
This implementation maintains a decreasing monotonic stack.
|
|
|
|
```python
|
|
def mono_stack(insert_entries):
|
|
stack = []
|
|
for entry in insert_entries:
|
|
# Pop smaller (or equal) values so stack stays decreasing.
|
|
while stack and stack[-1] <= entry:
|
|
stack.pop()
|
|
# Do something with the popped item here
|
|
stack.append(entry)
|
|
```
|
|
|
|
:::tip
|
|
In interview problems, the stack usually stores indices instead of values. You can read the value from the original array when needed, and the index gives you distance information such as **"how many steps away is the next greater element."**
|
|
:::
|
|
|
|
For an array `nums`, if index `j` pops when you process index `i`, then `i` is the first index to the right that satisfies the stack condition for `j`. In a next-greater-element problem, that means `nums[i]` is the next greater value for `nums[j]`.
|
|
|