Queue Using Two Stacks
You will be given ‘Q’ queries. You need to implement a queue using two stacks according to those queries. Each query will belong to one of these three types:
1 ‘X’: Enqueue element ‘X’ into the end of the nth queue. Returns true after the element is enqueued.
2: Dequeue the element at the front of the nth queue. Returns -1 if the queue is empty, otherwise, returns the dequeued element.
Note:
Enqueue means adding an element to the end of the queue, while Dequeue means removing the element from the front of the queue.
Input Format:
The first line of input contains an integer ‘Q’ denoting the number of queries.
The next ‘Q’ lines specify the type of operation/query to be performed on the data structure.
Each query contains an integer ‘P’ denoting the type of query.
For query of type 1, the integer ‘P’ is equal to 1 and it is followed by one integer ‘X’ denoting the element on which operation is to be performed.
For query of type 2, the integer ‘P’ is equal to 2 which dequeues the element.
Output Format:
For each query, return the output returned after performing the corresponding operation on the data structure.
Note:
You don’t need to print anything. It has already been taken care of. Just implement the given functions.
Constraints:
1 <= Q <= 10^5
1 <= P <= 2
1 <= X <= 10^5
Time limit: 1 sec
CodingNinjas
author
2y
Making the Enqueue operation costly
In this approach, we make sure that the oldest element added to the queue stays at the top of the stack, the second oldest below it and so on. To achieve this, we wi...read more
CodingNinjas
author
2y
Making the dequeue operation costly
In this approach, we insert a new element onto the stack 'STK1' simply by calling the push() function, but doing so will push our first element towards the bottom of...read more
Help your peers!
Add answer anonymously...
Top Springworks Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Top HR questions asked in Springworks Software Developer Intern
>
Springworks Software Developer Intern 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