#155

Min Stack

specialist · 750 · lc medium +31 · 57.8% accepted · 15,893 likes · top 54%

play →

Description

Build a stack that also supports constant-time retrieval of the minimum element.

Implement the MinStack class:

- MinStack() initializes the stack object.

- void push(int val) pushes val onto the stack.

- void pop() removes the top element.

- int top() returns the top element.

- int getMin() returns the current minimum element in the stack.

All five operations must run in O(1) time.

Example 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Example 2:

Output
[null,null,null,null,-3,null,0,-2]

Example 3:

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24