DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 86

The task is to implement a Queue by using Stack.

The boilerplate code

class Queue {
  enqueue(element) { 
    // add new element to the rare
  }
  peek() { 
    // get the head element
  }
  size() { 
    // return count of element
  }
  dequeue() {
    // remove the head element
  }
}

Enter fullscreen mode Exit fullscreen mode

A Queue follows the First In, First Out rule.

Create an array that stores all the queue elements, and a pointer that points to the front of the queue.

this.items = [];
this.head = 0;
Enter fullscreen mode Exit fullscreen mode

To add an element to the end of the queue

enqueue(element) {
  this.items.push(element);
}
Enter fullscreen mode Exit fullscreen mode

To get the front element

peek() {
  return this.size() === 0 ? undefined : this.items[this.head];
}
Enter fullscreen mode Exit fullscreen mode

To know how many valid elements are in the queue

size() {
  return this.items.length - this.head;
}
Enter fullscreen mode Exit fullscreen mode

To remove the front element

dequeue() {
  if (this.size() === 0) return undefined;

  const value = this.items[this.head];
  this.head++;

  return value;
}
Enter fullscreen mode Exit fullscreen mode

Dequeue stores the front value, moves the pointer forward and returns the removed value. If the queue is empty, undefined is returned.

The final code

class Queue {
  constructor() {
    this.items = [];
    this.head = 0;
  }
  enqueue(element) { 
    // add new element to the rare
    this.items.push(element);
  }
  peek() { 
    // get the head element
    return this.size() === 0 ? undefined : this.items[this.head];
  }
  size() { 
    // return count of element
    return this.items.length - this.head;
  }
  dequeue() {
    // remove the head element
    if(this.size() === 0) return undefined;

    const value = this.items[this.head];
    this.head++

    if(this.head >  50 && this.head * 2 >= this.items.length) {
      this.items = this.items.slice(this.head);
      this.head = 0;
    }
    return value;
  }
}

Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)