Minimum Stack
Minimum Stack
Minimum Stack
Problem: Design and implement a stack that supports push(),pop(), top() and
retrieving the minimum element in constant time.
Implement a Stack class, which supports the following methods in O(1) time
complexity.
void push() : Insert element onto the stack.
void pop() : Remove the top element from the stack.
int top() : Retrieve the top element in the stack.
int getmin() : Retrieve the minimum element in the stack.
Push 2
Example
Push 6 2 Pop 2 Push 1
Push 3 6 6 6 Pop 6 1
Push 4 3 3 3 3 3 3
4 4 4 4 4 4 4
Current
Minimum 4 3 3 2 3 3 1
1 import java.util.*;
2 class Mystack {
3 Stack<Integer> s;
4 Stack<Integer> a;
5 Mystack() {
6 s = new Stack<Integer>();
7 a = new Stack<Integer>();
8 }
9 void getMin() {
10 if(a.isEmpty())
11 System.out.println(“Stack is Empty”);
12 else
13 System.out.println(“Minimum element : “ + a.peek());
14 }
15 void peek(){
16 if(s.isEmpty()) {
17
System.out.println(“Stack is Empty”);
18
19 return ;
20 }
21
22
1 integer t=s.peek();
2 System.out.print(“Top most element:” + t);
3
}
4
5 void pop() {
6 int t = s.pop();
7 if(s.isEmpty()) {
8
System.out.println(“Stack is Empty”);
9
10 return ;
11 }
12 else
13
System.out.println(“Removed element : “ + t);
14
15 if(t == a.peek())
16 a.pop();
17 }
18
19
20
21
22
1 void push(int x) {
2 if ( s.isEmpty()) {
3
4 s.push(x);
5 a.push(x)
6 System.out.println(“ Number Inserted: “+ x);
7
8 return ;
9 }
10 else {
11
12 s.push(x);
13 System.out.prinln(“ Number Inserted: “ +x);}
14 if ( x<= a.peek() )
15
16 a.push(x);
17 }
18 };
19
20
21
22
1 public class Main {
2 public static void main(String args[]) {
3
4 Mystack s=new Mystack();
5 Scanner sc = new Scanner(System.in);
6 int n=sc.nextInt();
7
8 for( int i=0;i<n;i++) {
9 int m=sc.nextInt();
10 s.push(m);
11
12 }
13 s.getMin();
14 s.pop();
15
s.getMin();
16
17 s.pop();
18 s.peek();
19 }
20
}
21
22
THANK YOU