The Min Stack solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Min Stack
C++, Python and TypeScript solutions for Min Stack.
Solution files
Python•min-stack/synced-solution.py
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self) -> None:
val = self.stack.pop()
if val == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
C++•min-stack/synced-solution.cpp
class MinStack {
private:
stack<int> st;
stack<int> min_st;
public:
MinStack() {
}
void push(int val) {
st.push(val);
if (min_st.empty() || val <= min_st.top()) {
min_st.push(val);
}
}
void pop() {
int val = st.top();
st.pop();
if (val == min_st.top()) {
min_st.pop();
}
}
int top() {
return st.top();
}
int getMin() {
return min_st.top();
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(val);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
TypeScript•min-stack/synced-solution.ts
class MinStack {
private stack: number[] = [];
private minStack: number[] = [];
push(val: number): void {
this.stack.push(val);
if (this.minStack.length === 0 || val <= this.minStack[this.minStack.length - 1]) {
this.minStack.push(val);
}
}
pop(): void {
const val = this.stack.pop();
if (val === this.minStack[this.minStack.length - 1]) {
this.minStack.pop();
}
}
top(): number {
return this.stack[this.stack.length - 1];
}
getMin(): number {
return this.minStack[this.minStack.length - 1];
}
}