Min Stack
Design a stack that supports the following operations in O(1) time:
- push(val) — Push an element onto the stack.
- pop() — Remove the element on top of the stack.
- top() — Get the top element of the stack.
- getMin() — Retrieve the minimum element in the stack.
Implement the MinStack class.
Example 1
Input
7 push -2 push 0 push -3 getMin pop top getMin
Output
-3 0 -2
Explanation
After pushing -2, 0, and -3, the minimum is -3.
After removing -3, the top is 0 and the minimum becomes -2.
Example 2
Input
8 push 2 push 1 push 3 getMin pop getMin top pop
Output
1 1 1
Explanation
he minimum after pushing 2, 1, 3 is 1.
After removing 3, the minimum remains 1, and the top is also 1.
Constraints
Hints:
Hint 1
Use an additional stack to keep track of the minimum value at every level of the main stack.
Hint 2
Whenever you push a value, also store the minimum of the current value and the previous minimum.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 10, 2026
Last updated
Aug 10, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output