Striver-SDE-Sheet

Repository containing solution for #SdeSheetChallenge by striver

View the Project on GitHub

Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Implement the MinStack class:

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();

TIP

Time Complexity: O(1) for all the solutions.

Space Complexity: Extra O(N) Space used.


Using 2 Vectors

Code

class MinStack {
    vector<int> st;
    vector<int> mnStack;
public:
    MinStack() {
        mnStack.push_back(INT_MAX);
    }

    void push(int val) {
        st.push_back(val);
        mnStack.push_back(min(val,mnStack.back()));
    }

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

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

    int getMin() {
        return mnStack.back();
    }
};

Using 1 vector

Code

class MinStack{
    vector<int> st;
    int minElem;

public:
    MinStack() { minElem = INT_MAX; }

    void push(int val){
        if(val<=minElem){
            st.push_back(minElem);
            minElem = val;
        }
        st.push_back(val);
    }

    void pop(){
        int top = st.back();
        st.pop_back();
        if (top == minElem){
            minElem = st.back();
            st.pop_back();
        }
    }

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

    int getMin() { return minElem; }
};

Using vector of pair

Code

#include <bits/stdc++.h>

// Implement class for minStack.
class minStack {
    vector<pair<int, int>> mnStack;

public:
    // Constructor
    minStack() { }

    // Function to add another element equal to num at the top of stack.
    void push(int num)
    {
        if (mnStack.empty())
            mnStack.push_back({ num, num });
        else
            mnStack.push_back({ num, min(mnStack.back().second, num) });
    }

    // Function to remove the top element of the stack.
    int pop()
    {
        if (mnStack.empty())
            return -1;
        int topNum = mnStack.back().first;
        mnStack.pop_back();
        return topNum;
    }

    // Function to return the top element of stack if it is present. Otherwise return -1.
    int top()
    {
        if (mnStack.empty())
            return -1;
        else
            return mnStack.back().first;
    }

    // Function to return minimum element of stack if it is present. Otherwise return -1.
    int getMin()
    {
        if (mnStack.empty())
            return -1;
        else
            return mnStack.back().second;
    }
};