docs(docs): add YouTube video and detailed monotonic stack explanation with Python example

This commit is contained in:
Prad Nukala committed 2026-10-06 12:53:26 -04:00
1 parent ceaa9a2e75
commit 115b901fbe
1 file changed
+31
@@ -3,3 +3,34 @@ 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]`.