Help in clearing pop() method

A reader asked us the following question:

“The pop() method in class ‘newStack’ is popping from both minStack and mainStack, however, minStack does not have all the values from mainStack so can not be synced IMO. Need little help in what I may be missing here?”

This is Alina from Educative. Thank you for reaching out to us and giving your feedback.

For every value pushed into the mainStack, we also make a push to the minStack. If a new value is less than the value of the current top of minStack, we push it to minStack to declare it as the new minimum. Otherwise, we push the current top of minStack again into minStack. Thus, there can be multiple instances of the same minimum in the minStack to ensure that both stacks (minStack and mainStack) contain an equal number of items.

Now let’s come to the popping part. When we pop from the newStack, we pop from both the minStack and mainStack to ensure that they have an equal number of items. Hence, minStack does contain as many values as the mainStack, but the values may not be the same. Hope this helps! Let me know if you need other clarifications.

We hope Educative has inspired you to further your learning! If you have any further concerns/questions/comments, please let us know.

Best Regards,
Alina Fatima | Developer Advocate