How would you maintain a stack so that whenever you pop from the stack, you know the minimum element in the stack? The algorithm should have a constant complexity
Thanks in advance
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Ok, here’s what you need to do..
You need to maintain some
data structurecontaining information of each element you insert regarding, what was theminimumandsecond minimumvalue at the time when you inserted that element..So, you want to have information like this: –
For each Element pushed ->
This information will be needed when you
popthat element from stack.. So, you would know that, whether you arepoppingminimum value or not.. If yes, then you can replace the currentminimumvalue with theminimum valuebefore pushing this element.. If not, then there will be no change inminimumvalue at that time..For E.g: –
Suppose currently you have following element in stack: –
And you push a value 8.. Then you have two values to maintain..
(minimum value before 8 in pushed, i.e. 2, and miminum value after 8
is inserted, i.e. 2): –
And if you push a value 1, then
minimum_before_insertionis 2,and
minimum_after_insertionis 1: –Now your stack is :-
Now, if you
pop, You will see that forvalue 1: –So, popping will alter the minimum value, So, you change the current minimum value with the
minimum_value_before_pushof 1.. So, again your minimum is 2..Your current stack becomes : –
Now, let’s check whether this algorithm works for
duplicateelement : –Suppose you want to push a
value 2again..Then you go on and
pop, you see that forvalue 2,min_value_after_pushis 2, so this means popping it will alter the minimum value.. So you replace this value withmin_value_before_push, which is also 2.. Which is what we wanted..NOTE: – One Benefit of this Algorithm is that, you won’t need to do much comparison.. Just a comparison with
current_minimum_valuewhile pushing.. And a comparison withcurrent_minimum_valuewhen youpop..You can try to proceed to think what
data structurecan you have..