HomeLeetcode232. Implement Queue using Stacks - Leetcode Solutions

232. Implement Queue using Stacks – Leetcode Solutions

Description

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

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

Examples:

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Solution in Python

Python
class MyQueue:
    def __init__(self):
        # Stack1 will be used to handle the push operation
        # Stack2 will be used to reverse the order to simulate FIFO behavior
        self.stack1 = []  # Main stack where new elements are pushed
        self.stack2 = []  # Temporary stack used for pop/peek operations
    
    def push(self, x: int) -> None:
        # Simply push the element to the top of stack1
        self.stack1.append(x)

    def pop(self) -> int:
        # If stack2 is empty, move all elements from stack1 to stack2 to reverse order
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        # The top of stack2 will now be the front of the queue, so pop and return it
        return self.stack2.pop()

    def peek(self) -> int:
        # Similar to pop(), but we don't remove the element. Just return the top of stack2
        if not self.stack2:
            while self.stack1:
                self.stack2.append(self.stack1.pop())
        return self.stack2[-1]  # Peek at the top of stack2
    
    def empty(self) -> bool:
        # If both stacks are empty, the queue is empty
        return not self.stack1 and not self.stack2

Explanation:

  1. Stacks: We use two stacks (stack1 and stack2) to simulate a queue.
    • stack1: Acts as the stack to handle all push operations.
    • stack2: Temporarily holds elements in reversed order to simulate the FIFO queue behavior.
  2. Push:
    • When pushing an element, it’s added to stack1.
  3. Pop:
    • To remove the front element, we need to reverse the order of the elements in stack1. If stack2 is empty, we pop all elements from stack1 and push them onto stack2, so the front of the queue (i.e., the oldest element) is now at the top of stack2.
    • Finally, we pop from stack2.
  4. Peek:
    • Similar to pop, but instead of removing the front element, we just return it from stack2.
  5. Empty:
    • If both stack1 and stack2 are empty, the queue is empty.

Solution in Javascript

JavaScript
var MyQueue = function() {
    // Initialize two stacks: stack1 for push operations and stack2 for pop/peek operations
    this.stack1 = []; // Stack used for incoming elements
    this.stack2 = []; // Stack used for reversing the order of elements
};

/** 
 * Pushes element x to the back of the queue.
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function(x) {
    // Push element x onto stack1
    this.stack1.push(x);
};

/**
 * Removes the element from the front of the queue and returns it.
 * @return {number}
 */
MyQueue.prototype.pop = function() {
    // If stack2 is empty, transfer elements from stack1 to stack2
    if (this.stack2.length === 0) {
        while (this.stack1.length > 0) {
            this.stack2.push(this.stack1.pop());
        }
    }
    // The element to be removed is on top of stack2
    return this.stack2.pop();
};

/**
 * Returns the element at the front of the queue.
 * @return {number}
 */
MyQueue.prototype.peek = function() {
    // If stack2 is empty, transfer elements from stack1 to stack2
    if (this.stack2.length === 0) {
        while (this.stack1.length > 0) {
            this.stack2.push(this.stack1.pop());
        }
    }
    // The element at the front is now on top of stack2
    return this.stack2[this.stack2.length - 1];
};

/**
 * Returns true if the queue is empty, false otherwise.
 * @return {boolean}
 */
MyQueue.prototype.empty = function() {
    // The queue is empty if both stacks are empty
    return this.stack1.length === 0 && this.stack2.length === 0;
};

Solution in Java

Java
import java.util.Stack;

class MyQueue {
    // Initialize two stacks: stack1 for push operations and stack2 for pop/peek operations
    private Stack<Integer> stack1;
    private Stack<Integer> stack2;

    // Constructor to initialize the stacks
    public MyQueue() {
        stack1 = new Stack<>(); // Stack used for incoming elements
        stack2 = new Stack<>(); // Stack used for reversing the order of elements
    }
    
    /**
     * Pushes element x to the back of the queue.
     * @param x the element to be pushed
     */
    public void push(int x) {
        // Push the element onto stack1
        stack1.push(x);
    }
    
    /**
     * Removes the element from the front of the queue and returns it.
     * @return the element at the front of the queue
     */
    public int pop() {
        // If stack2 is empty, transfer all elements from stack1 to stack2
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        // Pop and return the element from the top of stack2
        return stack2.pop();
    }
    
    /**
     * Returns the element at the front of the queue without removing it.
     * @return the element at the front of the queue
     */
    public int peek() {
        // If stack2 is empty, transfer all elements from stack1 to stack2
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }
        // Return the element at the top of stack2 without removing it
        return stack2.peek();
    }
    
    /**
     * Returns true if the queue is empty, false otherwise.
     * @return true if the queue is empty, false otherwise
     */
    public boolean empty() {
        // The queue is empty if both stacks are empty
        return stack1.isEmpty() && stack2.isEmpty();
    }
}

Solution in C#

C#
using System.Collections.Generic;

public class MyQueue
{
    // Two stacks: stack1 for push operations and stack2 for pop/peek operations
    private Stack<int> stack1;
    private Stack<int> stack2;

    // Constructor to initialize the stacks
    public MyQueue()
    {
        stack1 = new Stack<int>(); // Stack used for incoming elements
        stack2 = new Stack<int>(); // Stack used for reversing the order of elements
    }
    
    // Pushes element x to the back of the queue
    public void Push(int x)
    {
        // Push the element onto stack1
        stack1.Push(x);
    }
    
    // Removes the element from the front of the queue and returns it
    public int Pop()
    {
        // If stack2 is empty, transfer all elements from stack1 to stack2
        if (stack2.Count == 0)
        {
            while (stack1.Count > 0)
            {
                stack2.Push(stack1.Pop());
            }
        }
        // Pop and return the element from the top of stack2
        return stack2.Pop();
    }
    
    // Returns the element at the front of the queue without removing it
    public int Peek()
    {
        // If stack2 is empty, transfer all elements from stack1 to stack2
        if (stack2.Count == 0)
        {
            while (stack1.Count > 0)
            {
                stack2.Push(stack1.Pop());
            }
        }
        // Return the element at the top of stack2 without removing it
        return stack2.Peek();
    }
    
    // Returns true if the queue is empty, false otherwise
    public bool Empty()
    {
        // The queue is empty if both stacks are empty
        return stack1.Count == 0 && stack2.Count == 0;
    }
}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular