Last active
April 12, 2020 20:02
-
-
Save KodeSeeker/9849433 to your computer and use it in GitHub Desktop.
Stack that Support Push, Pop, and GetMin in Constant Time
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
/* | |
Design a stack that supports push, pop, and retrieving the minimum element in constant time. Can you do this? | |
Solution: | |
Keep a stack of minimums: Extra memory | |
*/ | |
public class StackWithMin{ | |
private Stack<Integer> normalstk=new Stack<Integer>(); | |
private Stack<Integer> minstk=new Stack<Integer>(); | |
// while pushing into | |
//Push into minstk if inserted element is smaller than smallest input element or if minstk is empty | |
// | |
public void push(int input) | |
{ | |
if(minstk.isEmpty()|| (x<minstk.top() ) | |
minstk.push(input); | |
//push into normal stk anyways | |
normalstk.push(input); | |
} | |
//while popping if element is =minstk.top then pop from minstk too | |
public int pop() | |
{ | |
if normalstk.isEmpty() | |
return -1; //stk is empty | |
int ret=normalstk.pop(); | |
if(ret==minstk.top()) | |
minstk.pop();//pop from minstk as well! | |
return ret; | |
} | |
//get the minimum at any point | |
public int getMin() | |
{ | |
if(minstk.isEmpty()) | |
return -1; | |
return minstk.pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
if(minstk.isEmpty()|| (x<minstk.top() )
needs to beif(minstk.isEmpty()|| (x<=minstk.top() )
, What do you think?following test case fails: