KatInterview

232. Implement Queue using Stacks

EasySolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation: Two-Stack Approach (Amortized O(1))

This problem requires simulating a First-In, First-Out (FIFO) queue using only two Last-In, First-Out (LIFO) stacks. The optimal solution achieves amortized O(1) time complexity for each queue operation.

Solution

Implement Queue using Stacks in Python

class MyQueue:

    def __init__(self):
        # Use two lists to simulate stacks
        self.input_stack = []  # For push operations
        self.output_stack = [] # For pop/peek operations

    def push(self, x: int) -> None:
        """
        Pushes element x to the back of the queue.
        """
        self.input_stack.append(x)

    def pop(self) -> int:
        """
        Removes the element from in front of queue and returns that element.
        """
        # Ensure output_stack has the front element
        self.peek()
        return self.output_stack.pop()

    def peek(self) -> int:
        """
        Get the front element.
        """
        # If output_stack is empty, transfer elements from input_stack
        if not self.output_stack:
            while self.input_stack:
                self.output_stack.append(self.input_stack.pop())
        return self.output_stack[-1]

    def empty(self) -> bool:
        """
        Returns whether the queue is empty.
        """
        # The queue is empty if both stacks are empty
        return not self.input_stack and not self.output_stack


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

Implement Queue using Stacks in Java

import java.util.Deque;
import java.util.ArrayDeque;

class MyQueue {

    // Use Deque as a stack. input stack for push operations.
    private Deque<Integer> input;
    // output stack for pop/peek operations.
    private Deque<Integer> output;

    public MyQueue() {
        input = new ArrayDeque<>();
        output = new ArrayDeque<>();
    }
    
    // Pushes element x to the back of the queue.
    public void push(int x) {
        // All new elements go to the input stack.
        input.push(x);
    }
    
    // Removes the element from the front of the queue and returns it.
    public int pop() {
        // Ensure the front element is in the output stack.
        transferInputToOutput();
        return output.pop();
    }
    
    // Returns the element at the front of the queue.
    public int peek() {
        // Ensure the front element is in the output stack.
        transferInputToOutput();
        return output.peek();
    }
    
    // Returns true if the queue is empty, false otherwise.
    public boolean empty() {
        // The queue is empty if and only if both stacks are empty.
        return input.isEmpty() && output.isEmpty();
    }

    // Helper method to move elements from input to output stack.
    // This move only happens when the output stack is empty, which is key
    // for the amortized O(1) complexity.
    private void transferInputToOutput() {
        if (output.isEmpty()) {
            while (!input.isEmpty()) {
                output.push(input.pop());
            }
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

Implement Queue using Stacks in C++

class MyQueue {
private:
    // input stack for push operations
    std::stack<int> input;
    // output stack for pop/peek operations
    std::stack<int> output;

    // Helper function to ensure the front element is in the output stack.
    // This is the core of the amortized O(1) complexity.
    void transferInputToOutput() {
        // Only transfer if the output stack is empty.
        if (output.empty()) {
            // Move all elements from input to output.
            while (!input.empty()) {
                output.push(input.top());
                input.pop();
            }
        }
    }

public:
    MyQueue() {
        
    }
    
    // Pushes element x to the back of the queue.
    void push(int x) {
        input.push(x);
    }
    
    // Removes the element from the front of the queue and returns it.
    int pop() {
        // Ensure output stack has the front element.
        transferInputToOutput();
        int frontElement = output.top();
        output.pop();
        return frontElement;
    }
    
    // Returns the element at the front of the queue.
    int peek() {
        // Ensure output stack has the front element.
        transferInputToOutput();
        return output.top();
    }
    
    // Returns true if the queue is empty, false otherwise.
    bool empty() {
        // The queue is empty if both stacks are empty.
        return input.empty() && output.empty();
    }
};

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue* obj = new MyQueue();
 * obj->push(x);
 * int param_2 = obj->pop();
 * int param_3 = obj->peek();
 * bool param_4 = obj->empty();
 */

Implement Queue using Stacks in TypeScript

class MyQueue {
    // Use two arrays to simulate stacks.
    private inputStack: number[];  // For push operations
    private outputStack: number[]; // For pop/peek operations

    constructor() {
        this.inputStack = [];
        this.outputStack = [];
    }

    // Pushes element x to the back of the queue.
    push(x: number): void {
        this.inputStack.push(x);
    }

    // Helper function to move elements from input to output stack.
    // This is the core logic for amortized O(1) operations.
    private transferIfNeeded(): void {
        if (this.outputStack.length === 0) {
            while (this.inputStack.length > 0) {
                // 'pop' returns T | undefined, but problem constraints guarantee
                // we won't call it on an empty array, so we can use non-null assertion '!'.
                this.outputStack.push(this.inputStack.pop()!);
            }
        }
    }

    // Removes the element from the front of the queue and returns it.
    pop(): number {
        this.transferIfNeeded();
        // As per problem constraints, pop/peek are always on valid queues,
        // so outputStack will not be empty here.
        return this.outputStack.pop()!;
    }

    // Returns the element at the front of the queue.
    peek(): number {
        this.transferIfNeeded();
        // outputStack will have the front element at its end (top of stack).
        return this.outputStack[this.outputStack.length - 1];
    }

    // Returns true if the queue is empty, false otherwise.
    empty(): boolean {
        return this.inputStack.length === 0 && this.outputStack.length === 0;
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * var obj = new MyQueue()
 * obj.push(x)
 * var param_2 = obj.pop()
 * var param_3 = obj.peek()
 * var param_4 = obj.empty()
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.