Loading RustViz Engine...
Design a stack that retrieves the minimum element in O(1) constant time.
This problem is currently in blueprint template mode. Once the concept foundation is finalized, live in-browser WebAssembly compilation and test assertion runners will be enabled here.
pub struct MinStack {
stack: Vec<i32>,
min_stack: Vec<i32>,
}
impl MinStack {
pub fn new() -> Self { Self { stack: Vec::new(), min_stack: Vec::new() } }
pub fn push(&mut self, val: i32) {
self.stack.push(val);
let min = self.min_stack.last().copied().map_or(val, |m| m.min(val));
self.min_stack.push(min);
}
pub fn pop(&mut self) -> Option<i32> {
self.min_stack.pop();
self.stack.pop()
}
pub fn get_min(&self) -> Option<i32> {
self.min_stack.last().copied()
}
}