LeetCode 232: Implement Queue using Stacks

StackDesignQueue

Problem Description

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.

Solutions

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());
        }
    }
}

Loading editor...