Min Stack Problem

Min Stack Problem — ExecCode Medium DSA Practice

Solve the Min Stack problem on ExecCode. Free online medium DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.

Problem description

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Implement the MinStack class with: - push(val): push val onto the stack - pop(): remove the element on top of the stack - top(): get the top element - getMin(): retrieve the minimum element in the stack All operations must run in O(1) average/worst-case time as required by the problem.

Examples

Input {"ops": [5, 3, 7, "getMin", 2, "getMin", "pop", "getMin", "top", "pop", "getMin"]}; Output [3, 2, 3, 7, 3]. Input {"ops": [-2, 0, -3, "getMin", "pop", "top", "getMin"]}; Output [-3, 0, -2]. Input {"ops": [1, 2, -1, "getMin", "pop", "getMin"]}; Output [-1, 1]

Constraints

-2³¹ ≤ val ≤ 2³¹ - 1 Methods pop, top and getMin operations will always be called on non-empty stacks. At most 3 × 10⁴ calls will be made to push, pop, top, and getMin.

Practice Min Stack free on ExecCode. Browse DSA problems, topic map, and placement guides.