Question presented to candidate: "Design a stack class in Python that supports push, pop, top and get_min, where every one of those operations runs in O(1) time. Talk me through how you keep the minimum correct after a pop."
What a strong answer should cover:
- Why a single current-minimum variable fails after popping the minimum.
- Storing (value, minimum so far) on each entry, or an auxiliary
minsstack that is pushed on<=. - All four operations O(1); O(n) extra space, and when the two-stack version saves memory.
- The duplicate-minimum case, and why
<instead of<=breaks it. - Python specifics: a list of tuples as the stack;
min(self.stack)would be O(n);stack[-1]on an empty list raisesIndexError; Python ints never overflow, so the encoded-difference trick is safe here.
Clarifying questions expected:
- "What should top or get_min do on an empty stack?"
- "Can values repeat?"
Code / implementation expected: Yes โ a Python class backed by a list of (value, min) tuples.