Min Stack in Java: Explanation & Practice
Design stack that supports getMin in O(1)
Problem summary
Design a stack that supports push, pop, top, and retrieving minimum element in constant time.
Starter code
public class Main {
public static void main(String[] args) {
// Implement MinStack
// push(-2), push(0), push(-3)
// getMin() → -3
// pop()
// top() → 0
// getMin() → -2
// Print operations in order
}
}Expected output and test cases
- push -2,0,-3; getMin; pop; top; getMin
Min: -3 Top: 0 Min: -2
- push -2,0,-1; getMin twice
Min: -2 Min: -2
- push 1; getMin
Min: 1
Hints
- Use two stacks: one for values, one for minimums
- When pushing, also push to min stack if <= current min
- When popping, also pop from min stack if value equals current min
- Alternative: store pairs of (value, minSoFar)
Related Data Structures & Algorithms exercises
- Practice Daily Temperatures in Java
- Practice Largest Rectangle in Histogram in Java
- Practice Binary Tree Inorder Traversal in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler