Implement Queue Using Stacks

  • Adobe Interview Questions
  • Apple Interview Questions
  • Microsoft Interview Questions
  • Oracle Interview Questions

Implement the following operations of a queue using stacks.

  • push(x) — Push element x to the back of queue.
  • pop() — Removes the element from in front of queue.
  • peek() — Get the front element.
  • empty() — Return whether the queue is empty.


MyQueue queue = new MyQueue();



queue.peek(); // returns 3

queue.pop(); // returns 3

queue.empty(); // returns false


  • You must use only standard operations of a stack — which means only push to top, peek/pop from top, size, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).


Queue is FIFO (First in first out) and Stack is LIFO (Last In First Out). To convert stack into queue, we need two stacks to store and retrieve elements. We will push all the elements in one stack but at the time when we need front element in queue we will simply reverse the elements by remove elements one by one from one stack to the other. This process will give the correct output as the elements are then arranged in the form of a queue.



 class MyQueue {
    Stack<Integer> s1, s2;
    public MyQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();

    public void push(int x) {

    public int pop() {
        return s2.pop();

    /** Get the front element. */
    public int peek() {
        return s2.peek();

    public boolean empty() {
        return s2.size() == 0;

Complexity Analysis:

  • Time Complexity: O(n)

  • Space Complexity: O(1)

Scroll to Top

Full Stack Integrated Bootcamp Free Trial

  • Please enter a number from 7000000000 to 9999999999.