#C13531. Sorted Stack
Sorted Stack
Sorted Stack
You are tasked with implementing a SortedStack class that stores integers in a stack data structure so that its elements are always sorted in ascending order. The smallest element should be at the top of the stack.
The SortedStack
class should support the following operations:
push(val)
: Inserts an integerval
into the stack while maintaining the sorted order.pop()
: Removes the element at the top of the stack. If the stack is empty, do nothing.peek()
: Returns the top element of the stack (i.e. the smallest element) without removing it. Returns-1
if the stack is empty.isEmpty()
: ReturnsTrue
if the stack is empty, otherwise returnsFalse
.
Note: The stack must always be sorted in ascending order after every operation. In other words, if you perform a series of push and pop operations, the peek
operation must always return the smallest element currently in the stack.
Constraints:
- The number of elements in the stack will be in the range \([0, 10^5]\).
- \(-10^6 \leq val \leq 10^6\).
- You will make at most \(10^5\) calls to
push
,pop
,peek
, andisEmpty
.
Input/Output is handled via standard input and output. The first line of input contains an integer n, the number of operations. Each of the following n lines contains one operation in one of the following forms:
push x
wherex
is an integer.pop
peek
isEmpty
For each peek
and isEmpty
operation, output the result on a new line.
Example:
Input: 10 push 3 push 2 push 4 peek pop peek pop peek pop isEmpty</p>Output: 2 3 4 True
inputFormat
The first line of input is an integer n
which represents the number of operations. The next n
lines describe the operations to be performed on the SortedStack. Each operation is one of the following forms:
push x
(wherex
is an integer)pop
peek
isEmpty
outputFormat
For every peek
and isEmpty
operation, output the result to the standard output on a new line. For a peek
operation, output the smallest element in the stack (or -1
if the stack is empty), and for an isEmpty
operation, output True
if the stack is empty, otherwise False
.
10
push 3
push 2
push 4
peek
pop
peek
pop
peek
pop
isEmpty
2
3
4
True
</p>