LeetCode 232: Implement Queue using Stacks Solution

Master LeetCode problem 232 (Implement Queue using Stacks), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

232. Implement Queue using Stacks

Problem Explanation

Explanation

To implement a queue using two stacks, we can use one stack for pushing elements and the other stack for popping elements. When we need to pop or peek at the front of the queue, we can transfer elements from the push stack to the pop stack to maintain the correct order.

Algorithm:

  1. For the push operation, simply push the element onto the push stack.
  2. For the pop or peek operation, if the pop stack is empty, transfer all elements from the push stack to the pop stack.
  3. Perform the pop or peek operation on the pop stack.
  4. For the empty operation, check if both push and pop stacks are empty.

Time Complexity:

  • Push: O(1)
  • Pop/Peek: Amortized O(1)
  • Empty: O(1)

Space Complexity:

O(n) where n is the number of elements in the queue.

Solution Code

import java.util.Stack;

class MyQueue {
    private Stack<Integer> pushStack;
    private Stack<Integer> popStack;

    public MyQueue() {
        pushStack = new Stack<>();
        popStack = new Stack<>();
    }

    public void push(int x) {
        pushStack.push(x);
    }

    public int pop() {
        if (popStack.isEmpty()) {
            transferElements();
        }
        return popStack.pop();
    }

    public int peek() {
        if (popStack.isEmpty()) {
            transferElements();
        }
        return popStack.peek();
    }

    public boolean empty() {
        return pushStack.isEmpty() && popStack.isEmpty();
    }

    private void transferElements() {
        while (!pushStack.isEmpty()) {
            popStack.push(pushStack.pop());
        }
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 232 (Implement Queue using Stacks)?

This page provides optimized solutions for LeetCode problem 232 (Implement Queue using Stacks) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 232 (Implement Queue using Stacks)?

The time complexity for LeetCode 232 (Implement Queue using Stacks) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 232 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 232 in Java, C++, or Python.

Back to LeetCode Solutions