Medium Data Structures Stacks & Queues
Design a stack that supports push, pop, and getMin in O(1) time.
Answer
Use two approaches: (1) Two stacks - main stack for elements, auxiliary stack for minimums. Push to both when element <= current min. Pop from both when popping the minimum. (2) Single stack with pairs storing (value, currentMin). (3) Without extra space: store encoded value = 2*value - minAtThatTime when value is new minimum; decode when popping. All achieve O(1) operations.
IIT Certified
Master These Concepts with IIT Certification
175+ hours of industry projects. Get placed at Bosch, Tata Motors, L&T and 500+ companies.
Relevant for Roles
Software Engineer Backend Developer Systems Developer