CJCoding With Joseph
15free / daySign inCreate account

Min Stack

Build a class MinStack that behaves like a normal stack of ints but can also report its smallest element in constant time — getMin() must not scan the stack.

Implement these public methods:
1. void push(int x) — pushes x on top
2. void pop() — removes the top element (never called on an empty stack by the tests)
3. int top() const — returns the top element without removing it
4. int getMin() const — returns the smallest element currently in the stack
5. bool empty() const — returns true when the stack has no elements

Example: after push(2), push(1), push(3) the test prints getMin(), then top(), then pops twice and prints getMin() again, one value per line (see Expected Output).

The tests print empty() as the words true or false.

Do NOT write a main function.

Expected Output:

1
3
2
true
5
5
5
5
true

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
STL ContainersStacks
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (cout, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.