# Get Minimum Element from Stack in O(1)

Design a stack to get minimum element from stack in O(1) (constant time).

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

9  ==> Top
1
2
3

Then if we call getMin() method, It will return 1 in O(1) (constant time). In a stack, Element which pushed last in the stack is the first element to be popped out. Think for a moment how we can solve this problem.

Check for Balanced Parentheses using Stack

Queue using Two Stacks

## How to Get Minimum Element from Stack in Constant Time

We can solve this problem using two stack.

i) Declare two stack. One is main stack and other stack will hold only minimum element.

ii) Then we modify the push operation.

After this push operation, both the stack will be look like this. Now, if i call peek() method on second stack then i get minimum element from a stack in O(1).

Subscribe Our Tutorials

Get minimum element from stack in O(1)

In this video tutorial, I have explained how to get minimum element from stack in O(1) time complexity.

Java program to reverse a string using stack

## Get Minimum Element from Stack in O(1) – Java Code

We have discussed how we can find minimum element from stack in O(1). Let’s write a java code to implement this logic.

Find next greater element in an array