Loading section...

Min-Stack and Max-Stack in O(1)

Concepts: pyMinStack, pyMaxStack, pyAuxStack

The min-stack problem: design a stack that supports push, pop, top, and get_min, all in O(1) time. The naive approach — scan the entire stack to find the minimum — is O(n) per get_min. The trick: maintain a parallel auxiliary stack that tracks the current minimum at every level. When you push a value, also push the new minimum onto the auxiliary stack. When you pop, pop from both. get_min just reads the top of the auxiliary stack. Why the Auxiliary Stack Stays Correct The key invariant: min_stack[i] stores the minimum of all elements from stack[0] to stack[i]. When you push, you compute the new minimum by comparing the incoming value to the previous minimum (min_stack top). When you pop, you remove the top of both stacks simultaneously. The invariant is maintained because the minimum of st