#C8949. Min Stack Design
Min Stack Design
Min Stack Design
You are required to design a stack data structure that supports the following operations:
- push(x): Add an integer x onto the stack.
- pop(): Remove the element from the top of the stack. If the stack is empty, do nothing.
- getMin(): Retrieve the minimum element in the stack. If the stack is empty, return -1.
Internally, you must design your data structure such that the getMin operation can be performed in constant time. This is a typical design problem where you may need to maintain an auxiliary structure.
In mathematical terms, if the stack stores a sequence \( s_1, s_2, \ldots, s_n \), then: \[ getMin() = \min_{1 \leq i \leq n} s_i \]
You will be provided with a series of commands to operate on the stack. The input will be given via standard input and the output via standard output.
inputFormat
The first line of input contains a single integer n which represents the number of operations to be performed on the stack. Each of the following n lines contains a command in one of the following formats:
push x
— where x is an integer to be pushed onto the stack.pop
— which removes the top element of the stack.getMin
— which prints the minimum element in the stack.
It is guaranteed that the commands are valid. For any getMin
command on an empty stack, print -1
.
outputFormat
For each getMin
command, output the corresponding minimum element on a new line. If the stack is empty during a getMin
operation, output -1
.
10
push 3
push 5
getMin
push 2
push 1
getMin
pop
getMin
pop
getMin
3
1
2
3
</p>