Algo-Sim › Low-Level Design

Min Stack

Medium · Low-Level Design · step through it in Java, Python and C++ on your own input

A stack with O(1) getMin: every entry stores the minimum of itself and everything below it.

Problem

Design a stack that supports push(val), pop(), top() and getMin(), which returns the smallest value currently on the stack. Every operation must take constant time.

Constraints

Edge cases to test

Follow-up questions

Can you save memory?
Keep a second stack that only gets a value when it is ≤ the current minimum, or store differences from the minimum.
What about a min-queue?
Two min-stacks make a queue with O(1) amortized min, or use a monotonic deque.

Solution

Java

class MinStack {
    // Each entry keeps its value and the minimum of everything at or below it.
    private final Deque<int[]> stack = new ArrayDeque<>();

    public void push(int val) {
        int min = stack.isEmpty() ? val : Math.min(val, stack.peek()[1]);
        stack.push(new int[] {val, min});
    }

    public void pop() {
        stack.pop();
    }

    public int top() {
        return stack.peek()[0];
    }

    public int getMin() {
        return stack.peek()[1];
    }
}

Python

class MinStack:
    # Each entry keeps its value and the minimum of everything at or below it.
    def __init__(self):
        self.stack = []

    def push(self, val):
        low = val if not self.stack else min(val, self.stack[-1][1])
        self.stack.append((val, low))

    def pop(self):
        self.stack.pop()

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

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

C++

#include <bits/stdc++.h>
using namespace std;

class MinStack {
  public:
    // Each entry keeps its value and the minimum of everything at or below it.
    deque<vector<int>> stack = {};

    void push(int val) {
        int min = stack.empty() ? val : std::min(val, stack.back()[1]);
        stack.push_back(vector<int>{val, min});
    }

    void pop() {
        stack.pop_back();
    }

    int top() {
        return stack.back()[0];
    }

    int getMin() {
        return stack.back()[1];
    }
};

More Low-Level Design problems