Solution Review: Min Stack

Let's discuss the solution of the challenge posed in the previous lesson.

Solution: A two-stack class

Weā€™ll make a new class consisting of two stacks: mainStack and minimumStack. The class will have the following functions:

  • Push()
  • Pop()
  • Min()

Letā€™s see what each function will do:

  • Push: Push an element to the top of mainStack. It compares the new value with the value at the top of minimumStack. If the new value is smaller, then we push the new value into minimumStack. Otherwise, we push the minimum value at the top of the minimumStack to itself again.

  • Pop: Pops an element from the top of mainStack and returns. It also pops an element from the top of minimumStack.

  • Min: Reads from the top of the minimumStack. This value will be the minimum value.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.