Skip to content

Commit 9f278e1

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 155 Min Stack
1 parent b91af14 commit 9f278e1

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
4040
- [122 Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/)
4141
- [125 Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/)
4242
- [128 Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/description/)
43+
- [155 Min Stack](https://leetcode.com/problems/min-stack/description/)
4344
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
4445
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
4546
- [202 Happy Number](https://leetcode.com/problems/happy-number/description/)
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class MinStack:
2+
"""
3+
Design a stack that supports push, pop, top, and retrieving the
4+
minimum element in constant time.
5+
6+
Implement the MinStack class:
7+
- MinStack() initializes the stack object.
8+
- void push(int val) pushes the element val onto the stack.
9+
- void pop() removes the element on the top of the stack.
10+
- int top() gets the top element of the stack.
11+
- int getMin() retrieves the minimum element in the stack.
12+
13+
You must implement a solution with O(1) time complexity for each function.
14+
"""
15+
16+
def __init__(self):
17+
self.stack = []
18+
19+
def push(self, val: int) -> None:
20+
if not self.stack:
21+
self.stack.append((val, val))
22+
else:
23+
last_min_val = self.getMin()
24+
min_val = min(last_min_val, val)
25+
self.stack.append((val, min_val))
26+
27+
def pop(self) -> None:
28+
self.stack.pop()
29+
30+
def top(self) -> int:
31+
return self.stack[-1][0]
32+
33+
def getMin(self) -> int:
34+
return self.stack[-1][1]
35+
36+
37+
# Your MinStack object will be instantiated and called as such:
38+
# obj = MinStack()
39+
# obj.push(val)
40+
# obj.pop()
41+
# param_3 = obj.top()
42+
# param_4 = obj.getMin()

tests/test_155_min_stack.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
from awesome_python_leetcode._155_min_stack import MinStack
2+
3+
4+
def test_func():
5+
min_stack = MinStack()
6+
min_stack.push(-2)
7+
min_stack.push(0)
8+
min_stack.push(-3)
9+
assert min_stack.getMin() == -3
10+
min_stack.pop()
11+
assert min_stack.top() == 0
12+
assert min_stack.getMin() == -2

0 commit comments

Comments
 (0)