#155
Medium Algorithms Min stack
Stack Design
57.7% acceptance
Jan 12, 2026
15876
989
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
You must implement a solution with O(1) time complexity for each function.
Solution
Rust
Time O(n)
Space O(n)
* impl MinStack {
* fn new() -> Self {
* }
* fn push(&self, val: i32) {
* }
* fn pop(&self) {
* }
* fn top(&self) -> i32 {
* }
* fn get_min(&self) -> i32 {
* }
* }
*/
impl MinStack {
fn new() -> Self {
MinStack {
stack: Vec::new(),
min_stack: Vec::new(),
}
}
fn push(&mut self, val: i32) {
self.stack.push(val);
if self.min_stack.is_empty() || val <= *self.min_stack.last().unwrap() {
self.min_stack.push(val);
}
}
fn pop(&mut self) {
if let Some(val) = self.stack.pop() {
if Some(&val) == self.min_stack.last() {
self.min_stack.pop();
}
}
}
fn top(&self) -> i32 {
*self.stack.last().unwrap()
}
fn get_min(&self) -> i32 {
*self.min_stack.last().unwrap()
}
}