GreatFrontEnd

Queue

Languages
JS
Difficulty
Medium
Recommended Duration
15 mins

Implement a queue data structure in JavaScript that contains the following operations:

Constructor

Queue

Creates an instance of a Queue class that doesn't contain any items. The constructor not accept any arguments.

Methods

enqueue

Adds an item to the back of the queue.

  • Arguments
    • {*} item: The item to be added to the back of the queue.
  • Returns
    • {number}: The new length of the queue.
  • Time Complexity
    • O(1)

dequeue

Remove an item from the front of the queue.

  • Returns
    • {*} item: The item at the front of the queue if it is not empty, undefined otherwise.
  • Time Complexity
    • O(1)

isEmpty

Determines if the queue is empty.

  • Returns
    • {boolean}: true if the queue has no items, false otherwise.
  • Time Complexity
    • O(1)

front

Returns the item at the front of the queue without removing it from the queue.

  • Returns
    • {*}: The item at the front of the queue if it is not empty, undefined otherwise.
  • Time Complexity
    • O(1)

back

Returns the item at the back of the queue without removing it from the queue.

  • Returns
    • {*}: The item at the back of the queue if it is not empty, undefined otherwise.
  • Time Complexity
    • O(1)

length

Returns the number of items in the queue.

  • Returns
    • {number}: The number of items in the queue.
  • Time Complexity
    • O(1)

Examples

const queue = new Queue();
queue.isEmpty(); // true
queue.enqueue(1);
queue.enqueue(2);
queue.length(); // 2
queue.enqueue(3);
queue.front(); // 1
queue.back(); // 3
queue.dequeue(); // 1
queue.isEmpty(); // false

Similar Questions

Loading...