Implementing min-max stack with auxiliary stacks
The solution maintains three stacks: one for data, one for current minimums, and one for current maximums. On each push, it adds the new value to the data stack and updates the min and max stacks with the new min/max at that level to enable O(1) min/max retrievals; pop removes from all three stacks simultaneously.
Below is a straightforward implementation of a MinMaxStack in Python. All operations—push, pop, getMin, and getMax—run in O(1) time by maintaining two auxiliary stacks that track the running minimum and maximum at each stack depth.
class MinMaxStack:
def __init__(self):
self.main_stack = []
self.min_stack = []
self.max_stack = []
def push(self, value):
# Push the value onto the main stack
self.main_stack.append(value)
# Compute and store current min
if not self.min_stack:
self.min_stack.append(value)
else:
current_min = self.min_stack[-1]
self.min_stack.append(min(value, current_min))
# Compute and store current max
if not self.max_stack:
self.max_stack.append(value)
else:
current_max = self.max_stack[-1]
self.max_stack.append(max(value, current_max))
def pop(self):
if not self.main_stack:
raise IndexError("pop from empty stack")
# Pop from all three stacks to keep them in sync
self.min_stack.pop()
self.max_stack.pop()
return self.main_stack.pop()
def peek(self):
if not self.main_stack:
raise IndexError("peek from empty stack")
return self.main_stack[-1]
def getMin(self):
if not self.min_stack:
raise IndexError("getMin from empty stack")
return self.min_stack[-1]
def getMax(self):
if not self.max_stack:
raise IndexError("getMax from empty stack")
return self.max_stack[-1]
# Example usage:
if __name__ == "__main__":
stack = MinMaxStack()
stack.push(5) # min=5, max=5
stack.push(2) # min=2, max=5
stack.push(8) # min=2, max=8
stack.push(1) # min=1, max=8
print(stack.getMin()) # 1
print(stack.getMax()) # 8
stack.pop() # remove 1
print(stack.getMin()) # 2
print(stack.getMax()) # 8
How it works:
- Each
push also records the new “current min” and “current max” on dedicated stacks, so the top of these auxiliary stacks always corresponds to the minimum and maximum of the main stack at that depth.
getMin() and getMax() simply return the top of the respective auxiliary stack, so they are O(1).
pop() removes the top element from all stacks, keeping them synchronized.