Stop 18 · Data Structures & AlgorithmsTopics · 5/17

Queue

Part of the Full Stack Developer Roadmap

In short

Backend developers live with queues: job queues, message queues, request buffers. In DSA rounds, queues power breadth-first search. Same idea, first come first served.

A First-In-First-Out (FIFO) data structure — the natural fit for breadth-first traversal, task scheduling, and processing items in arrival order.

The purple blob at a bank counter serves the first person in a neat line holding tokens.

Think of it like this

The bank token counter

You take token 41, sit down, and wait. The counter calls 39, then 40, then you. Nobody who came later jumps ahead. New people join at the back, service happens at the front.

Watch it happen

Jobs waiting for a worker

enqueue(send email)
send email

Front of the queue is coloured

1/6The first job joins at the back of an empty queue, so it's also at the front.

The big ideas

What you need to know

Enqueue back, dequeue front

Items leave in the same order they arrived. That's FIFO: first in, first out.

array.shift() is O(n)

Removing index 0 shifts every other item. For big queues, track a head index or use a linked list.

BFS runs on a queue

Breadth-first search visits nodes level by level by queueing neighbours. It finds the shortest path in unweighted graphs.

Same idea in production

BullMQ, RabbitMQ and SQS are queues too. Producers add jobs; workers pull them off and process them.

See it in code

Walk through the code

ts
1class Queue<T> {2  private items: T[] = [];3  private head = 0;4 5  enqueue(item: T) { this.items.push(item); }6 7  dequeue(): T | undefined {8    if (this.head === this.items.length) return undefined;9    return this.items[this.head++]; // no shifting, O(1)10  }11 12  get size() { return this.items.length - this.head; }13}

1/4An array for storage and a head index that marks the front.

Instead of removing from the front, we move a head index forward. Both enqueue and dequeue stay O(1).

Save yourself the pain

Common mistakes

Oops

Using shift() for a BFS on a graph with lakhs of nodes.

Do this instead

Use a head index or a proper deque. shift() turns your O(n) BFS into O(n²).

Oops

Mixing up stack and queue in BFS vs DFS.

Do this instead

BFS uses a queue (level by level). DFS uses a stack or recursion (go deep first).

Your mission

Build and use a queue

~30 min

Quick check

Jobs A, B and C are added to a queue in that order. A worker takes one. Which job does it get?

Go deeper

  1. 1Implement a queue from scratch and compare its operations to a stack's.
  2. 2Use a queue to implement breadth-first search (BFS) on a graph or tree.
  3. 3Learn about circular queues and deques (double-ended queues) as variants.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge