AlgoMaster Logo

Min Stack

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Using Two Stacks

Intuition:

The idea here is to use two stacks. One stack will be used as a regular stack to store all the numbers, whereas the second stack (let's call it the minStack) will be used to keep track of the minimum value at each stage. Whenever we push an element, we'll also push the new minimum onto the minStack. When we pop an element, we'll also pop from the minStack to ensure both stacks stay synchronized.

Code:

2. Using Single Stack with Pair Value

Intuition:

Rather than using two separate stacks, we can optimize space by using a single stack, where each element in the stack is a pair consisting of the actual value and the minimum value up to that point.

Code:

3. Single Stack with Min Tracking

Intuition:

Another approach is to keep track of the minimum value in a variable. We push new values onto the stack, and if a new value is the new minimum, we first push the previous minimum onto the stack and then push the new value. The main advantage of this approach is that we use a single stack and minimum variables to efficiently track the minimum value.

Code: