Zero To DSAZero To DSA
Privacy Policy路FAQ路Report a Bug路Support on Ko鈥慺i
Daily TemperaturesTop K Frequent Elements

Implement Queue Using Stacks

easy
Time: O(1) amortized
Space: O(n)

Implement a first-in-first-out (FIFO) queue using only two stacks.

C#C#
public class MyQueue {
    private Stack<int> input = new();
    private Stack<int> output = new();

    public void Push(int x) {
        // TODO: implement your solution here
    }

    public int Pop() {
        // TODO: implement your solution here
        return 0;
    }

    public int Peek() {
        // TODO: implement your solution here
        return 0;
    }

    public bool Empty() {
        // TODO: implement your solution here
        return false;
    }
}

Constraints

  • All calls are valid (pop/peek on non-empty queue).

Examples

Input: MyQueue q = new MyQueue(); q.Push(1); q.Push(2); q.Peek(); // 1 q.Pop(); // 1 q.Empty(); // false
Output: null