educative.io

Pop() doesnt make minStack in sync with mainStack

int pop() {
    minStack->pop();
    return mainStack->pop();

}

Following pop() function line is not enough to bring minStack in sync with main stack, as in minStack, element which is being removed from main stack needs to be searched and then removed, and its not at the top of the minStack necessarily, as its top holds min element in stack!

minStack->pop();


Course: https://www.educative.io/collection/5642554087309312/5646276079124480
Lesson: https://www.educative.io/collection/page/5642554087309312/5646276079124480/5643517367943168

Hi @Chetan_Deshmukh !!
In our solution, the pop() function does not need to handle the case where it checks whether the element in minStack is also present in mainStack . The reason for this is our implementation of the push() function that keeps pushing the current minimum element in minStack on each push operation, meaning that the length of minStack and mainStack always remains the same. Due to this, the minimum element is repeatedly pushed to minStack on each successive push() operation, from the moment it was first pushed to mainStack and till the moment in which the next incoming element is less than the current minimum. Therefore, when popping from mainStack , we don’t have to worry if the current minimum element is lost from minStack since even though the current minimum is popped from minStack it’s new top will still hold the same current minimum, as long as that minimum has not been popped from mainStack

I hope it helps. Happy Learning :blush: