Get minimum element from stack | Practice | GeeksforGeeks

You are given N elements and your task is to Implement a Stack in which you can get minimum element in O(1) time.
Example 1:
Input:
push(2)
push(3)
pop()
getMin()
push(1)
getMin()
Output: 3 2 1
Explanation: In the first test case for
query 
push(2)  Insert 2 into the stack.
         The stack will be {2}
push(3)  Insert 3 into the stack.
         The stack will be {2 3}
pop()    Remove top element from stack 
         Poped element will be 3 the
         stack will be {2}
getMin() Return the minimum element
         min element will be 2 
push(1)  Insert 1 into the stack.
         The stack will be {2 1}
getMin() Return the minimum element
         min element will be 1

Your Task:
You are required to complete the three methods push() which take one argument an integer 'x' to be pushed into the stack, pop() which returns a integer poped out from the stack and getMin() which returns the min element from the stack. (-1 will be returned if for pop() and getMin() the stack is empty.)
Expected Time Complexity : O(1) for all the 3 methods.
Expected Auixilliary Space : O(1) for all the 3 methods.
Constraints:
1 <= Number of queries <= 100
1 <= values of the stack <= 100
0
harshitnjin 9 hours
Python Solution of O(1) time complexity for all functions
class stack:
    def __init__(self):
        self.s=[]
        

    def push(self,x):
        #CODE HERE
        if self.s:
            self.s.append([x,min(x,self.s[-1][1])])
        else:
            self.s.append([x,x])

    def pop(self):
        #CODE HERE
        if self.s:
            return self.s.pop()[0]
        return -1
        

    def getMin(self):
        #CODE HERE
        if self.s:
            return self.s[-1][1]
        return -1
0
naveenmnka1556 minutes ago
Python
def push(self,x):
    self.s.append(x)

def pop(self):
    if len(self.s)>0:
        return self.s.pop()
    return -1
    
def getMin(self):
	if len(self.s)>0:
        return min(self.s)
    return -1
0
arjundevmishra62 weeks ago
C++ solution :
class Solution{
    int minEle;
    multiset<int> st;
    stack<int> s;
    public:
    
       /*returns min element from stack*/
       int getMin(){
           if(s.size()==0)
           {
               return -1;
           }
           auto it = st.begin();
           return *it;
       }
       
       /*returns poped element from stack*/
       int pop(){
           if(s.size()==0)
           {
               return -1;
           }
           else{
               int a = s.top();
               s.pop();
               st.erase(st.lower_bound(a));
               return a;
           }
           //Write your code here
       }
       
       /*push element x into the stack*/
       void push(int x){
           s.push(x);
           st.insert(x);
       }
0
amit09
This comment was deleted.
-1
amit093 weeks ago
class Solution{
   int minEle = INT_MAX;
   stack<pair<int, int>> s;
   public:
   
      /*returns min element from stack*/
      int getMin(){
          if(s.empty()) return -1;
          return minEle;
      }
      
      /*returns poped element from stack*/
      int pop(){
          if(s.empty()) return -1;
          int val = s.top().first;
          s.pop();
          if(!s.empty()) minEle = s.top().second;
          return val;
      }
      
      /*push element x into the stack*/
      void push(int x){
          if(s.empty()) minEle = x;
          else 
          minEle  = std::min(x,minEle);
          s.push({x,minEle});
      }
};
0
amruthack11013 weeks ago
JAVA Solution
class GfG
{
    int min=Integer.MAX_VALUE;
    Stack<Integer> st=new Stack<>();
    boolean k=false;
    /*returns min element from stack*/
    int getMin()
    {
        if(st.isEmpty()){
            return -1;
        }
        if(k){
            for(int v:st){
                min=Math.min(min,v);
            }
            return min;
        }
        return min;
    }
    
    /*returns poped element from stack*/
    int pop()
    {
        if(st.isEmpty()){
            return -1;
        }
		if(st.peek()==min){
		    k=true;
		    min=Integer.MAX_VALUE;
		}
		return st.pop();
    }

    /*push element x into the stack*/
    void push(int x)
    {
	    st.push(x);
	    min=Math.min(min,x);
    }	
}
+1
himanshukug19cs1 month ago
 int minEle;   Stack<Integer> s= new Stack<>();
   /*returns min element from stack*/   int getMin()   {// Your code here
return s.empty() ? -1:minEle ;     }      /*returns poped element from stack*/   int pop()   {// Your code here if(s.empty())    return -1;if(s.peek()<minEle){        int min=minEle;    minEle=2*minEle-s.pop();       return min;}else    return s.pop();      }
   /*push element x into the stack*/   void push(int x)   {// Your code hereif(s.empty()){    s.push(x);    minEle=x;}else{    if(x>=minEle){         s.push(x);            }    else{        s.push(2*x-minEle);        minEle=x;    }      }        } 
+2
0aryabhatt1 month ago
class GfG {
    int minEle;
    Stack<Integer> s = new Stack<>();
    Stack<Integer> min = new Stack<>();

    int getMin() {
        if (s.isEmpty())
            return -1;
        return min.peek();
    }

    int pop() {
        if (s.isEmpty()) {
            return -1;
        }
        int x = s.pop();

        if (min.peek() == x) {
            min.pop();
        }
        return x;
    }

    void push(int x) {
        s.push(x);

        if (min.isEmpty())
            min.push(x);
        else {
            if (x <= min.peek()) {
                min.push(x);
            }
        }
    }
}
0
anshumankumar11 month ago
Simplest c++ solution
class Solution{   stack<int> st,s2;   public:      int getMin(){            if (st.empty())             return -1;         return s2.top();      }      int pop(){              if(st.empty())                    return -1;         if(st.top()==s2.top())           s2.pop();           int x=st.top();           st.pop();           return x;       }      void push(int x){          if(s2.empty()|| x<=s2.top())               s2.push(x);               st.push(x);      }};
-1
karmakaranupam111 month ago
java solution using extra stack :
class GfG
{
    int minEle;
    Stack<Integer> st = new Stack<>();
    Stack<Integer> min = new Stack<>();
    /*returns min element from stack*/
    int getMin()
    {
	// Your code here
	if(min.size() == 0) return -1;
	   return min.peek();
    }
    
    /*returns poped element from stack*/
    int pop()
    {
	// Your code here	
	if(st.size() == 0 ) return -1;
	int e = st.pop();
	if(e == min.peek()) min.pop();
	return e;
    }

    /*push element x into the stack*/
    void push(int x)
    {
	// Your code here
	st.push(x);
	if(min.size() == 0 || min.peek() >= x) min.push(x);

    }	
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.