algoadvance

Leetcode 232. Implement Queue using Stacks

Problem Statement

Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, pop, peek, and empty).

Implement the MyQueue class:

Notes:

Clarifying Questions

  1. Q: Are there any constraints on the values that can be pushed into the queue?
    • A: No, any integer values can be pushed into the queue.
  2. Q: Can we use other data structures apart from two stacks for internal usage?
    • A: No, you are limited to using only two stacks.
  3. Q: Is it necessary to handle exceptions for operations on an empty queue?
    • A: For this problem, you may assume that all operations are valid, so you do not need to handle exceptions.

Strategy

To implement a queue using two stacks, we can use two main stacks:

  1. Input Stack (stack_in): Used to handle incoming elements via the push operation.
  2. Output Stack (stack_out): Used to handle outgoing elements for pop and peek operations.

The main idea is to transfer elements from the input stack to the output stack when needed, ensuring that the order of elements in the output stack is such that the topmost element is the front of the queue.

Operations:

Code

import java.util.Stack;

class MyQueue {
    private Stack<Integer> stack_in;
    private Stack<Integer> stack_out;

    public MyQueue() {
        stack_in = new Stack<>();
        stack_out = new Stack<>();
    }

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

    public int pop() {
        if (stack_out.isEmpty()) {
            while (!stack_in.isEmpty()) {
                stack_out.push(stack_in.pop());
            }
        }
        return stack_out.pop();
    }

    public int peek() {
        if (stack_out.isEmpty()) {
            while (!stack_in.isEmpty()) {
                stack_out.push(stack_in.pop());
            }
        }
        return stack_out.peek();
    }

    public boolean empty() {
        return stack_in.isEmpty() && stack_out.isEmpty();
    }
}

Time Complexity

This implementation provides an efficient and correct solution to the problem of simulating a queue using two stacks.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI