-
Notifications
You must be signed in to change notification settings - Fork 387
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #857 from kotwani2883/main
Added code for Min Stack in constant time and space in Stack folder
- Loading branch information
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
}; |