Min Stack
Collapse Content
Show Content
Create a Stack that contains the standard push
and pop
methods. It should also contain another method min
that returns the minimum number in the Stack.
Extra Credit
All operations should take O(1) time.
Input / Output
You will be given multiple lists of input in the standard manner. If a number is -1
, pop off the top number from your stack, and print nothing. Otherwise, push the given number onto your stack, and then print the minimum number currently in the Stack
Sample Input
1 10 3 5 -1 -1 7 2 11 -1 -1 9
Sample Output
3 3 7 2 2 7
Challenge
Create a Stack and print the minimum number every time a new number is added.
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.
Comments
Sarick Shah
Feb 18, 6:50 PMmy code
I'm not sure how I'm supposed to restart the current min and set it to 7. Basically if i pop a bunch off and the new min is a bigger number it is still showing the current min i set from before. Any hints on what I'm doing wrong?
Paulo
Feb 26, 11:19 PMSo, how do I know if all my operations are correctly running at O(1)? I mean, I can say it in theory but do the platform perform any basic check? Doesn't looks like because any code I wrote the test is passing.
Learneroo
Mar 1, 11:00 AM@Paulo, currently you should analyze the running time on your own. The computer cannot check the running time, but in the future we may add larger tests cases that fail to complete in time for poor algorithms.
Sarick Shah
Mar 3, 12:00 AMI still don't know exactly what I'm doing wrong...
Sarick Shah
Mar 3, 12:45 AMwould it be easier to use a queue here?
Panashe Fundira
Jun 7, 9:17 PMHint: Constant running time, but not constant space complexity
thales
Aug 7, 12:58 PMPlease a hint. i cant figure it out. I keep sitting with an empty stack and other problems. Help.
thales
Aug 7, 1:38 PMI have fount a way, but i think its not really the good way. can i see a featured awnseranywere?
Learneroo
Aug 8, 10:18 PMHere's a possible solution.
Quinn
Jul 10, 8:59 AMWould have been nice if the system didn't think my solution was wrong just because I forgot to println() after each example. Otherwise, keep up the good work!
Anand
Jun 4, 5:59 AMi write the program in Big O O(1) .how i can see my extra credit score.
Learneroo
Jun 4, 6:38 PMAll correct answers get the same mark, but it's a personal challenge to see if you can get a good Big-O time.