How can we get Minimum of Stack in a Constant Time O(1).
💻 coding

How can we get Minimum of Stack in a Constant Time O(1).

1 min read 262 words
1 min read
ShareWhatsAppPost on X
  • 1The method getMinimum() allows retrieval of the minimum element in a stack in O(1) time using an auxiliary min stack.
  • 2The min stack stores the minimum values, pushing the new element or the current minimum during stack operations.
  • 3The implementation involves a main stack for data and a min stack to track minimums, ensuring efficient minimum retrieval.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The method getMinimum() allows retrieval of the minimum element in a stack in O(1) time using an auxiliary min stack."

How can we get Minimum of Stack in a Constant Time O(1).

It is required to create a method getMinimum() which will give us the minimum in the current stack in O(1) time complexity. we will be using another stack for this to store the minimum at any particular point in time.

We will take an auxiliary stack that maintains the minimum of all values in the stack. Also, assume that each element of the stack is less than it's below elements. For simplicity let us call the auxiliary stack as min stack.

When we pop the main stack, pop the min stack too. When we push the main stack, push either the new element or the current minimum, whichever is lower. At any point, if we want to get the minimum then wee justs need to return the top element fro the min stack. Let us take some example and trace out.

Java solution for the given problem is as below:

package askgif.linkedlist;

import java.util.Stack;

class MyStack{
	Stack<Integer> stack = new Stack<Integer>();
	Stack<Integer> minStack = new Stack<Integer>();
	
	public MyStack() {
		stack = new Stack<Integer>();
		minStack = new Stack<Integer>();
	}
	
	public void push(int data) {
		stack.push(data);
		if(minStack.isEmpty())
			minStack.push(data);
		else if(minStack.peek() > data)
			minStack.push(data);
	}
	
	public int pop() {
		if(stack.isEmpty())
			return 0;
		int data = stack.pop();
		if(minStack.peek() == data)
			minStack.pop();
		return data;
	}
	
	public void printMinimum() {
		System.out.println(minStack.peek());
	}
}

public class Stacks {

	public static void main(String[] args) {
		MyStack stack = new MyStack();
		stack.push(10);
		stack.push(5);
		stack.printMinimum();
		
		stack.push(15);
		stack.push(12);
		stack.printMinimum();
		stack.pop();
		stack.printMinimum();
		stack.pop();
		stack.printMinimum();
		stack.pop();
		stack.printMinimum();

	}

}
output:

5
5
5
5
10

Time Complexity: O(1)

Space Complexity: O(n) for an extra stack.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 8 August 2018 · 1 min read · 262 words

Part of AskGif Blog · coding

You might also like

How can we get Minimum of Stack in a Constant Time O(1). | AskGif Blog