32/36
Part 8 of 8 · Follow-upsLearn and do
A stack that always knows its minimum stores the smallest so far with each item
Push, pop and min(), all O(1). Store each item with the smallest value at or below it, so the minimum is always on top:
class MinStack:
def __init__(self):
# (value, smallest so far)
self.items = []
def push(self, x):
low = min(x, self.items[-1][1]) if self.items else x
self.items.append((x, low))
def pop(self):
return self.items.pop()[0]
def min(self):
return self.items[-1][1]
s = MinStack()
for x in [5, 3, 7, 3, 1]:
s.push(x)
print("push", x, "min", s.min())
for _ in range(4):
print("pop", s.pop(), "min", s.min())
Push 5, 3, 7, 3 and 1, then pop once. What does min() return?
Pick one to see what it prints.
Pick an answer above to see the rest