Data Structures · Sorting

Min-Stack — two arrays and a top pointer: push / pop / peek / getMin

📚 arr (elements) beside minArr (prefix minima), with top pointing at the top

live element (index ≤ top)minArr = prefix minimumthe cell touched by this operation
current minimum getMin()

🧾 Operation log (one row per call)

💬 Current operation

💻 The C++ class the exercise asks for

Yellow = the line being executed. Two key lines: arr[++top] = val and minArr[top] = min(minArr[top-1], val) — the first pushes the value, the second records the running minimum.

📄 Key points & why it is O(1)

1push(v): check full, then arr[++top]=v, minArr[top]=min(minArr[top-1],v)
2pop(): check empty, then clear both arrays at top and top--
3peek(): read arr[top], change nothing
4getMin(): read minArr[top] → O(1)
The blackboard example: push 3 → array=(3) minarr=(3) top=0; push 2 → (3,2)/(3,2) top=1; push 5 → (3,2,5)/(3,2,2) top=2; push 1 → (3,2,5,1)/(3,2,2,1) top=3; getMin() = 1; after popping 1 minarr retreats to 2, getMin() = 2.
Why is getMin O(1)? minArr[i] holds the minimum of arr[0..i].
· push: a new value can only be smaller than the running minimum or not affect it, so min(oldMin, v) is the new prefix minimum;
· pop: both arrays retreat by one, and minArr[top-1] is already the minimum of what remains — nothing to recompute.
That is what makes it faster than scanning (O(n)) on every getMin: O(n) extra space buys an O(1) query.

Edges (as the exercise asks): push on a full stack → Stack Overflow!; pop on empty → Stack Underflow!; peek / getMin on empty → Stack is empty!.
Common mistakes: (1) top must start at -1 (not 0), otherwise the first element is off by one; (2) popping must clear both arrays, or a later push reusing that slot reads a stale minimum; (3) the first element has no previous minArr entry — handle it separately (the code here uses top==0 ? val : ...).

📋 The four blackboard steps (array / minarr / top)

steppushedarray[]minarr[]topwhy
①3(3)(3)0first element: minarr[0] = 3
②2(3, 2)(3, 2)12 < 3 → minarr[1] = 2
③5(3, 2, 5)(3, 2, 2)25 > 2 → minarr[2] = 2 (keep the previous minimum)
④1(3, 2, 5, 1)(3, 2, 2, 1)31 < 2 → minarr[3] = 1

Rule: minarr[top] = min(minarr[top-1], array[top]); top is an index — it is -1 when empty and 0 after the first push (exactly step ①). getMin reads minarr[top] only; both arrays retreat together on pop, so nothing is recomputed.

Speed
Shortcuts: Space play/pause · ←→ step · R reset · E result