Skip to content

Commit 2938cd7

Browse files
committed
Minimum Stack
1 parent 9f5372f commit 2938cd7

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Min_Stack.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
2+
#
3+
# push(x) -- Push element x onto stack.
4+
# pop() -- Removes the element on top of the stack.
5+
# top() -- Get the top element.
6+
# getMin() -- Retrieve the minimum element in the stack.
7+
#
8+
# MinStack minStack = new MinStack();
9+
# minStack.push(-2);
10+
# minStack.push(0);
11+
# minStack.push(-3);
12+
# minStack.getMin(); --> Returns -3.
13+
# minStack.pop();
14+
# minStack.top(); --> Returns 0.
15+
# minStack.getMin(); --> Returns -2.
16+
17+
18+
class MinStack:
19+
20+
def __init__(self):
21+
"""
22+
initialize your data structure here.
23+
"""
24+
self.stack = []
25+
26+
def push(self, x):
27+
if len(self.stack) == 0:
28+
self.stack.append([x, x])
29+
else:
30+
self.stack.append([x, min(self.stack[-1][1], x)])
31+
32+
def pop(self):
33+
self.stack.pop()
34+
35+
def top(self):
36+
return self.stack[-1][0]
37+
38+
def getMin(self):
39+
return self.stack[-1][1]
40+
41+
# Your MinStack object will be instantiated and called as such:
42+
# obj = MinStack()
43+
# obj.push(x)
44+
# obj.pop()
45+
# param_3 = obj.top()
46+
# param_4 = obj.getMin()

0 commit comments

Comments
 (0)