Min Stack — LeetCode 155 Python Solution

MediumStackDesign
Problem
#155
Pattern
Stack
Reading time
5 min

The problem

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.

Example

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();

Python solution

Python
class MinStack:
    def __init__(self):
        self.stk1 = []
        self.stk2 = [inf]

    def push(self, val: int) -> None:
        self.stk1.append(val)
        self.stk2.append(min(val, self.stk2[-1]))

    def pop(self) -> None:
        self.stk1.pop()
        self.stk2.pop()

    def top(self) -> int:
        return self.stk1[-1]

    def getMin(self) -> int:
        return self.stk2[-1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 155. Min Stack is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 155. Min Stack?
LeetCode 155. Min Stack is rated Medium on LeetCode.
What is the time complexity of LeetCode 155. Min Stack?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 155. Min Stack?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 155. Min Stack cover?
LeetCode 155. Min Stack is tagged Stack and Design on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview