Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

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
Approach 1:
Min stack 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
3 class Mystack {
4 Stack<Integer> s;
5
6
Stack<Integer> a;
7 Mystack() {
8 s = new Stack<Integer>();
9
10 a = new Stack<Integer>();
11 }
12
13
void getMin() {
14 if(a.isEmpty())
15 System.out.println(“Stack is Empty”);
16
17 else
18 System.out.println(“Minimum element : “ + a.peek());
19
20
}
21
22
1 void peek(){
2
if(s.isEmpty()) {
3
4 System.out.println(“Stack is Empty”);
5 return ;
6
7 }
8 integer t=s.peek();
9
System.out.print(“Top most element:” + t);
10
11 }
12 void pop() {
13
14 int t = s.pop();
15 if(s.isEmpty()) {
16
System.out.println(“Stack is Empty”);
17
18 return ;
19 }
20
21 else
22 System.out.println(“Removed element : “ + t);
1 if( t == a.peek() )
2
3 a.pop();
4 }
5
6 void push(int x) {
7
if ( s.isEmpty()) {
8
9 s.push(x);
10
11 a.push(x)
12 System.out.println(“ Number Inserted: “+ x);
13
14 return ;
15 }
16
17 else {
18
19
s.push(x);
20 System.out.prinln(“ Number Inserted: “ +x);
21
22 }
1 if ( x<= a.peek() )
2
3 a.push(x);
4
}
5
6 };
7
8 public class Main {
9 public static void main(String args[]) {
10
11 Mystack s=new Mystack();
12
13 Scanner sc = new Scanner(System.in);
14 int n=sc.nextInt();
15
16 for( int i=0;i<n;i++) {
17
18
int m=sc.nextInt();
19 s.push(m);
20
21 }
22
1 s.getMin();
2
3 s.pop();
4 s.getMin();
5
6 s.pop();
7 s.peek();
8
9 }
10 }
11
12
13
14
15
16
17
18
19
20
21
22
THANK YOU

You might also like