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, peek, pop, and empty).

Implementation Requirements:

Constraints:

Clarifying Questions

  1. Should I assume the elements are non-negative integers, or can they also be negative?
    • Elements can be any integer.
  2. Is there a maximum number of elements that the queue should support?
    • No specific limit, handle as many elements as possible within the constraints of typical memory limits.
  3. Can we assume that pop and peek will not be called on an empty queue?
    • No, handle such cases gracefully, either by throwing an error or returning a specific value.

Strategy

To implement this queue using two stacks, we can use the following strategy:

This way, we ensure that the oldest elements are popped and peeked first, maintaining the queue order.

Code

Here is the C++ implementation of the MyQueue class:

#include <stack>

class MyQueue {
private:
    std::stack<int> input;
    std::stack<int> output;

public:
    MyQueue() {
    }
    
    void push(int x) {
        input.push(x);
    }
    
    int pop() {
        if (output.empty()) {
            while (!input.empty()) {
                output.push(input.top());
                input.pop();
            }
        }
        int val = output.top();
        output.pop();
        return val;
    }
    
    int peek() {
        if (output.empty()) {
            while (!input.empty()) {
                output.push(input.top());
                input.pop();
            }
        }
        return output.top();
    }
    
    bool empty() {
        return input.empty() && output.empty();
    }
};

Time Complexity

Therefore, while individual pop and peek operations may sometimes take linear time in the worst case when elements are moved between the stacks, on average, each operation runs in constant time.

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