Algo-Sim › Stacks & Monotonic Stack

Implement Queue using Stacks

Easy · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

Two stacks make a FIFO queue: push onto in, and pour in into out only when out is empty. Amortized O(1).

Problem

Build a first-in, first-out queue using only two stacks and their standard operations (push to top, pop from top, peek at top, size, is empty). Support push(x), pop() and peek(), which remove or return the front value, and empty().

Constraints

Edge cases to test

Follow-up questions

Why is it O(1) amortized?
Each value moves from in to out once, so n operations cost O(n) moves in total, even though one pop can move many.
How do you make a stack from queues?
Rotate the queue after each push so the newest value is at the front: O(n) push, O(1) pop (LC 225).

Solution

Java

class MyQueue {
    private final Deque<Integer> in = new ArrayDeque<>(), out = new ArrayDeque<>();

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

    public int pop() {
        peek();
        return out.pop();
    }

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

    public boolean empty() {
        return in.isEmpty() && out.isEmpty();
    }
}

Python

class MyQueue:
    def __init__(self):
        self.ins, self.out = [], []

    def push(self, x):
        self.ins.append(x)

    def pop(self):
        self.peek()
        return self.out.pop()

    def peek(self):
        if not self.out:
            while self.ins: self.out.append(self.ins.pop())
        return self.out[-1]

    def empty(self):
        return not self.ins and not self.out

C++

#include <bits/stdc++.h>
using namespace std;

class MyQueue {
  public:
    stack<int> in, out;

    void push(int x) {
        in.push(x);
    }

    int pop() {
        peek();
        int front = out.top();
        out.pop();
        return front;
    }

    int peek() {
        if (out.empty()) {
            while (!in.empty()) out.push(in.top()), in.pop();
        }
        return out.top();
    }

    bool empty() {
        return in.empty() && out.empty();
    }
};

More Stacks & Monotonic Stack problems