#155
Min Stack
medium· Stackruns: 0Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class with push, pop, top, and getMin methods.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 486
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
current_min = self.min_stack[-1] if self.min_stack else val
self.min_stack.append(min(val, current_min))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.