🔥 0
0
Lesson 6 of 10 12 min +80 XP

Queues

A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Think of a line at a coffee shop — the first person in line gets served first.

Queue Data Structure

Core Operations

All basic queue operations are O(1) — constant time!

OperationDescriptionTime
enqueue(x)Add element to rearO(1)
dequeue()Remove and return front elementO(1)
peek() / front()View front element without removingO(1)
isEmpty()Check if queue is emptyO(1)
size()Get number of elementsO(1)

Implementation

Using an Array

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

  enqueue(element) {
    this.items.push(element);
  }

  dequeue() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    return this.items.shift();
  }

  peek() {
    if (this.isEmpty()) {
      return "Queue is empty";
    }
    return this.items[0];
  }

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

  size() {
    return this.items.length;
  }
}

// Usage
const queue = new Queue();
queue.enqueue(10);
queue.enqueue(25);
queue.enqueue(42);
console.log(queue.peek());    // 10 (first in)
console.log(queue.dequeue()); // 10 (first out)
console.log(queue.peek());    // 25

Python Implementation

from collections import deque

class Queue:
    def __init__(self):
        self.items = deque()

    def enqueue(self, item):
        self.items.append(item)

    def dequeue(self):
        if not self.is_empty():
            return self.items.popleft()
        return None

    def peek(self):
        if not self.is_empty():
            return self.items[0]
        return None

    def is_empty(self):
        return len(self.items) == 0

Stack vs Queue

AspectStackQueue
PrincipleLIFOFIFO
Addpush() to topenqueue() to rear
Removepop() from topdequeue() from front
ExampleUndo buttonPrint queue
AlgorithmDFSBFS

Types of Queues

1. Simple Queue

Standard FIFO queue we've been discussing.

2. Circular Queue

The rear connects back to the front, efficiently using fixed-size arrays.

[_, _, 3, 4, 5]  →  [6, 7, 3, 4, 5]
      ↑  rear wraps around to front

3. Priority Queue

Elements have priorities; highest priority is dequeued first.

// Often implemented with a heap
// Used in: Dijkstra's algorithm, task scheduling

4. Double-Ended Queue (Deque)

Insert and delete from both ends.

const deque = [];
deque.push(1);      // Add to rear
deque.unshift(0);   // Add to front
deque.pop();        // Remove from rear
deque.shift();      // Remove from front

Real-World Applications

  • Print Queue — Documents printed in order received
  • Task Scheduling — CPU processes tasks in order
  • BFS Algorithm — Exploring graphs level by level
  • Message Queues — Kafka, RabbitMQ for async processing
  • Customer Service — Call centers, ticket systems

BFS with a Queue

function bfs(graph, start) {
  const visited = new Set();
  const queue = [start];
  visited.add(start);

  while (queue.length > 0) {
    const node = queue.shift(); // Dequeue
    console.log(node);

    for (const neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor); // Enqueue
      }
    }
  }
}

What's Next?

Next, we'll explore Linked Lists — a dynamic data structure where elements are connected through pointers, allowing efficient insertions and deletions.

🧠 Quick Quiz

Test your understanding of this lesson.

1

What does FIFO stand for in the context of queues?

2

Which operation removes an element from a queue?

3

Which algorithm commonly uses a queue?

Stacks