JS Built-ins
Algorithmsbeginner

Queue: Enqueue and Dequeue

πŸ“– Usage Example
const queue = [];
queue.push(1); queue.push(2);
queue.shift(); // 1 β€” first in, first out

A queue uses push/shift for FIFO (First In, First Out) behavior.

Queue Data Structure

A Queue is a First-In-First-Out (FIFO) data structure where elements are added at the back and removed from the front.

Operations:

  • enqueue(x): Add element x to the back
  • dequeue(): Remove and return the front element
  • size: Number of elements

Real-world example: Printer queue (first document printed is the first one sent to printer).

class Queue {
  enqueue(x: any): void {}
  dequeue(): any {}
  get size(): number {}
}

const q = new Queue()
q.enqueue(1)
q.enqueue(2)
q.dequeue() // 1
πŸ’‘ Hints (4)
  • β€’ Use an array internally to store elements.
  • β€’ enqueue() should append to the end using push().
  • β€’ dequeue() should remove from the front using shift().
  • β€’ size should return the array length.