Get Minimum Element From Stack in O(1)

Get minimum element from stack in O(1).

In this problem, we have to design a stack that supports push, pop, top, and retrieving the minimum element in constant time (O(1)).

      push(x) Push element x onto stack.

     pop() Removes the element on top of the stack.

     top() Get the top element.

     getMin() Retrieve the minimum element in the stack.

For example: Suppose, If we push the following elements in a stack.

9  ==> Top
1
2
3

Then if we call getMin() method, It should return 1 in O(1) (constant time).

Min Stack

In a stack data structure, Element which we pushed at last is the first element to be popped out. That’s why it is also known as LIFO (Last In First Out) data structure.

Now, Think how we can design a stack that supports getMin() in constant time (o(1)). At the end of this tutorial, i have mentioned the link of a video tutorial.

How to Design Min Stack to Get Minimum Element from Stack

We can solve this problem of min stack by using two stacks.

i) Declare two stacks. One is the main stack in which we push value as it is. In the second stack, we only push the minimum element present at that time.

ii) Whenever we perform push operation in a stack.

     a) Push the value as it is in a first stack.

     b) For the second stack, push only the minimum value. For minimum value, Compare the current value with the value present at the top of the stack.

After the push operation, both the stack will look like this. 

Get minimum element from stack in O(1)

Now, if peek() method is called on the second stack then we get the min element in O(1).

Find the Minimum Element in a Stack in O(1) – Java Code

We have discussed how we can design a min stack that supports getMin() operation in O(1). Let’s write a java code to implement this logic.

Find next greater element in an array

Programming Video Tutorials

In this video tutorial, I have explained how to find min element in a stack each time while elements are being pushed and popped.

Min stack – video tutorial

Check for Balanced Parentheses using Stack

Queue using Two Stacks

Java program to reverse a string using stack

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.