Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
1. Push(num): Push the given number in the stack.
2. Pop: Remove and return the top element from the stack if present, else return -1.
3. Top: return the top element of the stack if present, else return -1.
4. getMin: Returns minimum element of the stack if present, else return -1.
For Example:
For the following input:
1
5
1 1
1 2
4
2
3
For the first two operations, we will just insert 1 and then 2 into the stack which was empty earlier. So now the stack is => [2,1]
In the third operation, we need to return the minimum element of the stack, i.e., 1. So now the stack is => [2,1]
For the fourth operation, we need to pop the topmost element of the stack, i.e., 2. Now the stack is => [1]
In the fifth operation, we return the top element of the stack, i.e. 1 as it has one element. Now the stack is => [1]
So, the final output will be:
1 2 1
Input Format:
The first line of the input contains a single integer ‘T’ representing the no. of test cases.
The first line of each test case contains a single integer ‘N’, denoting the no. of the operations.
The next ‘N’ lines of each test case contain either of the operations in the following format: -
Push -> two space-separated integers, 1 and ‘X’ like “1 X”. We need to push ‘X’ on top of the stack.
Pop -> single integer 2. We need to remove the topmost element from the stack.
Top -> single integer 3. We need to return the topmost element from the stack.
getMin -> single integer 4, We need to return the minimum element of the stack if present and 0 otherwise.
Output Format:
For each test case, print the results of the operations performed on the stack separated by spaces.
Print output of each test case in a separate line.
Note:
You are not required to print anything; it has already been taken care of. Just implement the function and return the answer.
Constraints -
1 ≤ T ≤ 1000
1 ≤ N ≤ 100000
ΣN ≤ 200000
1 ≤ X ≤ (10^9)
Time Limit: 1 sec
CodingNinjas
author
2y
In this problem I just had to tell them my approach and there was discussion on my approach.
I used two stacks here one to store actual stack elements ( Elements_Stack ) and the other as an extra stack...read more
CodingNinjas
author
2y
Naive Simulation
The basic idea is to store two stacks. One for regular stack and one for storing prefix minimums of our regular stack. We store values at which our minimum changes so that those values...read more
Help your peers!
Add answer anonymously...
Top Jio Platforms Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Jio Platforms Software Developer
>
Jio Platforms Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app