Implementing Queue with Two Stacks

Your task is to implement a queue using two stacks. You are provided with ‘Q’ queries and need to handle them, where each query falls under one of these two operations:

  1. Enqueue an element ‘X’ to the end of the queue.
  2. Dequeue an element from the front of the queue.

Functionality:

  • For enqueue, return true after the element is enqueued.
  • For dequeue, return -1 if the queue is empty, otherwise return the dequeued element.

Example:

Input:
5
1 10
1 20
2
1 30
2
Output:
true
true
10
true
20
Explanation:

The given queries perform the following operations:

  • Enqueue 10: Returns true
  • Enqueue 20: Returns true
  • Dequeue: Returns 10 (dequeued)
  • Enqueue 30: Returns true
  • Dequeue: Returns 20 (dequeued)

Constraints:

  • 1 <= Q <= 10^5
  • 1 <= P <= 2
  • 1 <= X <= 10^5 (for enqueue operation)
  • Time limit: 1 sec
AnswerBot
2d

Implement a queue using two stacks with enqueue and dequeue operations.

  • Use two stacks to simulate a queue - one for enqueue and one for dequeue.

  • For enqueue operation, push elements onto the enqueue st...read more

Help your peers!
Add answer anonymously...
Springworks Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter