Skip to content

Commit

Permalink
Merge pull request #857 from kotwani2883/main
Browse files Browse the repository at this point in the history
Added code for Min Stack in constant time and space in Stack folder
  • Loading branch information
tanus786 authored Oct 31, 2022
2 parents 4c8f5d2 + 6c09d81 commit a352255
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions Stack/min_stack_Constant_time_space
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
class Solution{
int minEle;
stack<int> s;
public:

/*returns min element from stack*/
int getMin(){

//Write your code here
if(s.size() == 0)
return -1;
else
return minEle;
}

/*returns poped element from stack*/
int pop(){

//Write your code here
if(s.empty())
return -1;
if(s.top()>=minEle){
int ans = s.top();
s.pop();
return ans;
}
else{
int ans = minEle;
minEle = 2*minEle-s.top();
s.pop();
return ans;
}
}

/*push element x into the stack*/
void push(int x){

//Write your code here
if(s.empty()){
s.push(x);
minEle=x;
}
else if(x>=minEle)
s.push(x);
else{
s.push(2*x-minEle);
minEle=x;
}
}
};

0 comments on commit a352255

Please sign in to comment.