Clone a Graph: Build a Queue


In the context of graph traversal, explain the purpose of a queue data structure and how it is used in breadth-first traversal. Then, write a class in JavaScript called Queue that implements a queue using an array and has methods for adding an element to the end of the queue, removing an element from the front of the queue, and checking if the queue is empty.

Provide a sample input and output of how the queue class should work.


A queue is a linear data structure that follows the First In First Out (FIFO) principle. In the context of graph traversal, a queue is used in breadth-first traversal to keep track of nodes that have been visited but have unvisited neighbors. The algorithm traverses the graph level by level, visiting all the nodes in a level before moving on to the next level. To do this, it adds the unvisited neighbors of the current node to the queue and then dequeues the first node in the queue to visit its neighbors. This process continues until all nodes have been visited.

To implement a queue in JavaScript, we can use an array data structure. We can create a class called Queue with a constructor that initializes an empty array to store the elements in the queue. Then, we can implement the following methods:

  • onQueue: This method adds an element to the end of the queue.

  • dequeue: This method removes an element from the front of the queue.

  • isEmpty: This method checks if the queue is empty.

Here's how we can implement the Queue class in JavaScript:

class Queue {
  constructor() {
    this.items = [];

  onQueue(element) {

  dequeue() {
    if (this.isEmpty()) {
      return "underflow";
    return this.items.shift();

  isEmpty() {
    return this.items.length === 0;

To test the Queue class, we can create a new queue object and call its methods:

const myQueue = new Queue();

console.log(myQueue.dequeue()); // Output: 1
console.log(myQueue.dequeue()); // Output: 2

console.log(myQueue.isEmpty()); // Output: false

console.log(myQueue.dequeue()); // Output: 3
console.log(myQueue.isEmpty()); // Output: true

console.log(myQueue.dequeue()); // Output: underflow

Big O Complexity Analysis:

The time complexity of the onQueue, dequeue, and isEmpty methods in the Queue class is O(1), which means they take constant time to execute regardless of the size of the queue. The space complexity of the Queue class is O(n), where n is the maximum size of the queue. This is because we use an array to store the elements in the queue and the size of the array can grow up to n.

The onQueue and dequeue methods take constant time because we only add or remove one element from the queue each time they are called, regardless of the size of the queue. The isEmpty method also takes constant time because it only checks the length of the array, which is a constant-time operation in JavaScript.