Skip to content

Commit 7278291

Browse files
committed
Solved problem 155 : Min Stack
1 parent bad7156 commit 7278291

File tree

2 files changed

+85
-3
lines changed

2 files changed

+85
-3
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
### Problems Solved
1818

19-
| Total | 60 |
19+
| Total | 61 |
2020
|:---:|:---:|
2121

2222
#### Search By Topic
@@ -38,7 +38,7 @@
3838
| Math & Geometry | 4 |
3939
| Priority Queue | 3 |
4040
| Sliding Window | 2 |
41-
| Stack | 3 |
41+
| Stack | 4 |
4242
| Tries | 0 |
4343
| Two Pointers | 6 |
4444

@@ -47,7 +47,7 @@
4747
| Difficulty | Number |
4848
|:---|---:|
4949
| Easy | 48 |
50-
| Medium | 12 |
50+
| Medium | 13 |
5151
| Hard | 0 |
5252

5353
## Milestones

Stack/Medium/155_MinStack.cpp

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/*
2+
* Problem: 155
3+
* Name: Min Stack
4+
* Difficulty: Medium
5+
* Topic: Stack
6+
* Link: https://leetcode.com/problems/min-stack/
7+
*/
8+
9+
#include <bits/stdc++.h>
10+
using namespace std;
11+
12+
// Stack-Pair Approach
13+
// Stack will store pairs of {elements, relative-mininums}
14+
// push: O(1)
15+
// pop: O(1)
16+
class MinStack {
17+
private:
18+
stack<pair<int,int>> stack;
19+
20+
public:
21+
MinStack() {}
22+
23+
void push(int val) {
24+
if (stack.empty()){
25+
stack.push({val,val});
26+
}
27+
else {
28+
stack.push({val, min(stack.top().second, val)});
29+
}
30+
}
31+
32+
void pop() {
33+
stack.pop();
34+
}
35+
36+
int top() {
37+
return stack.top().first;
38+
}
39+
40+
int getMin() {
41+
return stack.top().second;
42+
}
43+
};
44+
45+
// Two-Stack Approach
46+
// main stack will store all elements like a regular stack
47+
// mins stack will only store "relative" minimum values
48+
// push: O(1)
49+
// pop: O(1)
50+
class MinStack {
51+
private:
52+
stack<int> main;
53+
stack<int> mins;
54+
55+
public:
56+
MinStack() {}
57+
58+
void push(int val) {
59+
main.push(val);
60+
if (mins.empty()){
61+
mins.push(val);
62+
}
63+
else if (val <= mins.top()){
64+
mins.push(val);
65+
}
66+
}
67+
68+
void pop() {
69+
if (main.top() == mins.top()){
70+
mins.pop();
71+
}
72+
main.pop();
73+
}
74+
75+
int top() {
76+
return main.top();
77+
}
78+
79+
int getMin() {
80+
return mins.top();
81+
}
82+
};

0 commit comments

Comments
 (0)