1. Single Vector with Linear getMin Search
Intuition
Store values in a single standard stack/array. When getMin() is invoked, linearly scan all elements to find and return the minimum.
Algorithm
- Step 1: Store elements in dynamic array
st. - Step 2:
push(x)->st.push_back(x). - Step 3:
pop()->st.pop_back(). - Step 4:
top()->st.back(). - Step 5:
getMin()-> iterate throughstand return the minimum.
#include <iostream>#include <vector>#include <algorithm> class MinStack { std::vector<int> st;public: MinStack() {} void push(int val) { st.push_back(val); } void pop() { st.pop_back(); } int top() { return st.back(); } int getMin() { return *std::min_element(st.begin(), st.end()); }}; int main() { MinStack minStack; minStack.push(-2); minStack.push(0); minStack.push(-3); std::cout << "Min: " << minStack.getMin() << std::endl; // -3 minStack.pop(); std::cout << "Top: " << minStack.top() << std::endl; // 0 std::cout << "Min: " << minStack.getMin() << std::endl; // -2 return 0;}Time & Space Complexity
- Time complexity:
push/pop/top: O(1), getMin: O(N)— getMin searches through all elements in the vector taking O(N) time. - Space complexity:
O(N)— O(N) space to store elements.
Why Brute Force Doesn't Scale:
Linear getMin search costs O(N) per call, timing out under 30,000 operations.
Optimal MinStack handles 30,000 mixed calls in <5ms.