LeetCode #155 Min Stack

Problem

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) – Push element x onto stack.
  • pop() – Removes the element on top of the stack.
  • top() – Get the top element.
  • getMin() – Retrieve the minimum element in the stack.

Example

1
2
3
4
5
6
7
8
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.

Solution

Method:

Time Complexity:

Space Complexity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class MinStack:
def __init__(self):
self.stack = []

def push(self, x):
if not self.stack:
self.stack.append((x,x))
else:
minimum = self.stack[-1][1]
self.stack.append((x, min(x, self.stack[-1][1])))

def pop(self):
self.stack.pop()[0]

def top(self):
return self.stack[-1][0]

def getMin(self):
return self.stack[-1][1]

or

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Node:
def __init__(self, val, min_val = float('inf')):
self.val = val
self.min_val = min(val, min_val)

class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = [Node(float('inf'))]
self.len = 0

def push(self, x):
"""
:type x: int
:rtype: void
"""
pre_node = self.stack[-1]
self.stack.append(Node(x, pre_node.min_val))
self.len += 1

def pop(self):
"""
:rtype: void
"""
if self.len > 0:
self.stack.pop()
self.len -= 1


def top(self):
"""
:rtype: int
"""
if self.len > 0:
return self.stack[-1].val

def getMin(self):
"""
:rtype: int
"""
if self.len > 0:
return self.stack[-1].min_val


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()