Monotonic Stack Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Monotonic Stack runs in O(n) time and O(n) space, in Rust as in every other language.
- ✓Vec<T> is the stack. push takes ownership, pop returns Option<T> rather than panicking, and last returns Option<&T>, so emptiness is encoded in the type instead of in a convention.
- ✓Write while let Some(&top) = stack.last() with the ampersand in the pattern, so that the usize is copied out of the borrow immediately.
- ✓The Rust trap: Dropping that ampersand is the classic error. while let Some(top) = stack.last() binds top as a &usize, which holds an immutable borrow of the vector alive across the whole loop body, so the stack.pop() inside fails to compile with E0502, cannot borrow stack as mutable because it is also borrowed as immutable.
- ✓Vec doubles its capacity on growth, and a monotonic stack can never hold more than n entries, so Vec::with_capacity(n) removes every reallocation from the hot loop.
What Monotonic Stack actually is
Monotonic Stack in Rust: what you actually reach for
Rust implementation
/// For each day, how many days until a warmer one. O(n) total.
pub fn daily_temperatures(temps: &[i32]) -> Vec<usize> {
let mut answer = vec![0usize; temps.len()];
// The stack can never exceed n entries: preallocate and never realloc.
let mut stack: Vec<usize> = Vec::with_capacity(temps.len());
for (i, &t) in temps.iter().enumerate() {
// The & in "Some(&top)" COPIES the usize out of the borrow, so the
// immutable borrow of "stack" ends here. Without it, "top" is a
// &usize whose borrow spans the body and stack.pop() below fails
// to compile with E0502.
while let Some(&top) = stack.last() {
if temps[top] >= t {
break;
}
stack.pop();
answer[top] = i - top;
}
stack.push(i);
}
answer
}
/// Largest rectangle in a histogram.
pub fn largest_rectangle(heights: &[u64]) -> u64 {
let mut stack: Vec<usize> = Vec::with_capacity(heights.len() + 1);
let mut best = 0u64;
for i in 0..=heights.len() {
let h = if i == heights.len() { 0 } else { heights[i] };
while let Some(&top) = stack.last() {
if heights[top] < h {
break;
}
stack.pop();
let height = heights[top];
let left = stack.last().map_or(-1i64, |&l| l as i64);
let width = i as i64 - left - 1;
best = best.max(height * width as u64);
}
stack.push(i);
}
best
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Monotonic Stack?
Vec<T> is the stack. push takes ownership, pop returns Option<T> rather than panicking, and last returns Option<&T>, so emptiness is encoded in the type instead of in a convention.
What is the most common Rust mistake when implementing Monotonic Stack?
Dropping that ampersand is the classic error. while let Some(top) = stack.last() binds top as a &usize, which holds an immutable borrow of the vector alive across the whole loop body, so the stack.pop() inside fails to compile with E0502, cannot borrow stack as mutable because it is also borrowed as immutable. The compiler is right and the fix is not to restructure the loop but to copy the value out at the binding site, which for a usize is free.
How does Monotonic Stack actually perform in Rust?
Vec doubles its capacity on growth, and a monotonic stack can never hold more than n entries, so Vec::with_capacity(n) removes every reallocation from the hot loop. Indices are usize with no boxing and no per-element allocation, so the stack is one contiguous buffer the prefetcher handles well. Time complexity is O(n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Student discounts on developer tools are collected on Noizz, tool by tool.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.