Skip to content

Stack Advanced

Table of Contents

3170. Lexicographically Minimum String After Removing Stars

155. Min Stack

  • LeetCode | LeetCode CH (Medium)

  • Tags: stack, design

  • Implement a stack that supports push, pop, top, and retrieving the minimum element in constant time.
155. Min Stack - Python Solution
# Stack
class MinStack:

    def __init__(self):
        self.stack = []

    def push(self, val: int) -> None:
        if self.stack:
            self.stack.append((val, min(val, self.getMin())))
        else:
            self.stack.append((val, val))

    def pop(self) -> None:
        self.stack.pop()

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

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


obj = MinStack()
obj.push(3)
obj.push(2)
obj.pop()
print(obj.top())  # 3
print(obj.getMin())  # 3
155. Min Stack - C++ Solution
#include <algorithm>
#include <climits>
#include <iostream>
#include <stack>
#include <utility>
using namespace std;

class MinStack {
    stack<pair<int, int>> st;

   public:
    MinStack() { st.emplace(0, INT_MAX); }

    void push(int val) { st.emplace(val, min(getMin(), val)); }

    void pop() { st.pop(); }

    int top() { return st.top().first; }

    int getMin() { return st.top().second; }
};

int main() {
    MinStack minStack;
    minStack.push(-2);
    minStack.push(0);
    minStack.push(-3);
    cout << minStack.getMin() << endl;  // -3
    minStack.pop();
    cout << minStack.top() << endl;     // 0
    cout << minStack.getMin() << endl;  // -2
    return 0;
}

1381. Design a Stack With Increment Operation

636. Exclusive Time of Functions

2434. Using a Robot to Print the Lexicographically Smallest String

895. Maximum Frequency Stack

1172. Dinner Plate Stacks

2589. Minimum Time to Complete All Tasks

716. Max Stack

  • LeetCode | LeetCode CH (Hard)

  • Tags: linked list, stack, design, doubly linked list, ordered set

Comments