Home › Company-wise questions › Microsoft › Min Stack ← Microsoft bank
Microsoft · Question 27 · Stacks
Min Stack Stacks Java code ⏱ O(1) 💾 O(n)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Approach Mirror new minima on a parallel stack.
Time O(1)Space O(n)
How it works 1 Push values; mirror new minima. 2 Pop from the min stack only when its top leaves. Sample input / output Input:
7
push -2
push 0
push -3
getMin
pop
top
getMin
Output:
[-3, 0, -2] Constraints Methods called on non-empty stack; values fit 32-bit.
Solution — read it, then walk it Flowchart Pseudocode
Time O(1)Space O(n)Loops 1Branches 6source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
yes no yes no ↻ repeat START import java.util.* DEFINE class Main DEFINE class MinStack Stack<Integer> stack Stack<Integer> minStack DEFINE MinStack() stack = new Stack<>() minStack = new Stack<>() DEFINE void push(int val) stack.push(val) if (minStack.isEmpty() || val <= minStack.peek()) minStack.push(val) DEFINE void pop() if (stack.pop().equals(minStack.peek())) minStack.pop() DEFINE int top() { return stack.peek(); } DEFINE int getMin() { return minStack.peek(); } DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE ops = sc.nextInt() MinStack ms = new MinStack() java.util.List<Object> out = new ArrayList<>() for (int i = 0; i < ops; i++) String op = sc.next() if (op.equals("push")) ms.push(sc.nextInt()) else if (op.equals("pop")) ms.pop() else if (op.equals("top")) out.add(ms.top()) else if (op.equals("getMin")) out.add(ms.getMin()) System.out.println(out) END start / end statement condition loop returns definition← Q26 · Valid Parentheses Q28 · Implement Queue using Stacks → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →