Labs ICT
โญ Pro Login

Queues

First in, first out โ€” the line at the store.

Queues

You know that feeling when you're waiting in line at the store? First person in line gets served first, new people join at the back. That's FIFO - First In, First Out - and that's exactly how queues work.

Queues are the opposite of stacks. While stacks are "last one standing" winners, queues are all about fairness and order. First come, first served. It's the data structure version of a polite society.

From operating systems to web servers, queues manage how tasks are processed. They ensure that no task is forgotten and everything gets handled in the order it arrived.

Core Operations

Two main moves: enqueue (add to back) and dequeue (remove from front). Both should be O(1) for efficiency. You can also peek at the front element without removing it, or check if the queue is empty.

In JavaScript, you can use push() to enqueue and shift() to dequeue. It's that simple. The array handles all the heavy lifting under the hood. Just remember that shift() is O(n) because everything shifts forward.

const queue = [];
queue.push("customer1");
queue.push("customer2");
queue.push("customer3");
console.log(queue.shift());
console.log(queue.shift());

Real-World Uses

Queues power some of the most important algorithms out there. Breadth-First Search (BFS) for graph traversal? Queue. Print job scheduling? Queue. Handling requests on a web server? Queue. Task scheduling in operating systems? Queue.

BFS uses queues to explore nodes level by level. It's like exploring a building floor by floor - you visit all rooms on one floor before moving to the next. This makes queues essential for shortest path algorithms.

function bfs(graph, start) {
  const visited = new Set();
  const queue = [start];
  visited.add(start);
  while (queue.length > 0) {
    const node = queue.shift();
    for (const neighbor of graph[node]) {
      if (!visited.has(neighbor)) {
        visited.add(neighbor);
        queue.push(neighbor);
      }
    }
  }
}

Message Queues

They're also used in message queues for distributed systems, where messages need to be processed in order. If you ever work with Kafka, RabbitMQ, or similar tools, you're essentially working with queues at scale.

The concept scales beautifully from simple arrays to distributed systems handling millions of messages per second. That's the power of understanding the fundamentals.

Try it Yourself โ†’

๐Ÿงช Quick Quiz

What data structure uses FIFO (First In, First Out)?