Min Stack Keeps Running Minimum
A second stack stores the running minimum beside each value, so push, pop, and min all stay O(1) without scanning the whole stack.
Code
// 用第二个栈保存“到此为止的最小值”,pop 时两个栈同步弹出,
// push/pop/min 都是常数时间,求 min 不需要遍历
struct MinStack {
values: Vec<i32>,
minimums: Vec<i32>,
}
impl MinStack {
fn new() -> Self {
Self { values: Vec::new(), minimums: Vec::new() }
}
fn push(&mut self, value: i32) {
let min = match self.minimums.last() {
Some(current) if *current < value => *current,
_ => value,
};
self.values.push(value);
self.minimums.push(min);
}
fn pop(&mut self) -> Option<i32> {
self.minimums.pop();
self.values.pop()
}
fn min(&self) -> Option<i32> {
self.minimums.last().copied()
}
}
fn main() {
let mut stack = MinStack::new();
stack.push(5);
stack.push(2);
stack.push(7);
println!("min after pushes: {:?}", stack.min()); // Some(2)
println!("pop: {:?}", stack.pop()); // Some(7)
println!("pop: {:?}", stack.pop()); // Some(2)
println!("min now: {:?}", stack.min()); // Some(5)
println!("pop: {:?}", stack.pop()); // Some(5)
println!("min on empty: {:?}", stack.min()); // None
}How it works
Everything that executes sits inside the functions new, push, pop and min.
Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
What to watch for
- No external surface — every behavior comes from the standard library.
Using it
The signature you will call most reads fn new() -> Self
The demo output is labeled (min after pushes:, pop:, min now:), so the printed output reads as a trace of the operations performed.
main sequences new, push, min and pop; executing the file runs that flow once.
The key statements that remain
let min = match self.minimums.last() {
Some(current) if *current < value => *current,
_ => value,
};
fn pop(&mut self) -> Option<i32> {
self.minimums.pop();
self.values.pop()
}
fn min(&self) -> Option<i32> {
self.minimums.last().copied()
}
Interactive Tools for This Topic
FAQ
- What does Min Stack Keeps Running Minimum print when run?
- Execute the whole file; each printed line is prefixed with a label like `min after pushes:`, `pop:`, `min now:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.