AlgoTales · Roadmap

Queue implementation

Beginner · 7 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A queue is a line where the first to arrive is the first to be served. You add at the back and remove from the front, and nobody jumps ahead. It is the basic structure for anything where fairness and arrival order matter.

Practical use cases

  • Web app: Print or export jobs waiting their turn. On a report page, many users click "Export to Excel" at the same time. Each request joins the back of a queue, and a worker takes jobs from the front one at a time. Everyone is served in the order they clicked, and the server is not overloaded by 100 exports running at once.
  • Web app: Customer support chat waiting line. A support widget shows "You are number 4 in the queue". New chats join at the back and agents take from the front. Because order is strictly first come first served, customers trust the number and are not upset by someone cutting in.
  • System: Streaming buffers and graph exploration. Video players hold upcoming data in a queue so playback is smooth. Search methods that explore a map or network level by level, like finding the fewest hops between two people, also use a queue to visit nearest places first.

The story: The Ticket Counter at the Railway Station

Early morning at the railway station. One ticket counter, thirty people. Nobody pushes, nobody cuts in. A new person joins at the back of the line, and the clerk always serves whoever has been waiting the longest, at the front.

Mira watched this and realised it is the exact opposite of the plate pile she saw at the wedding. A stack serves the newest. A queue serves the oldest. First in, first out.

And you already use queues every day without noticing: the print jobs waiting in the office printer, the emails Laravel is about to send in the background, the video frames buffered on your phone. All are lines of work, fair and orderly.

How to spot this problem, and where you need it

Many things arrive faster than they can be handled, and they must be processed one by one in the order they arrived, without losing or reordering any.

Signs you need it

  • The words "first come, first served", "waiting list", "in order of arrival", "process later" or "line" appear in the requirement.
  • Users complain that requests are lost, handled in a strange order, or cause a spike when many arrive together.
  • Your code removes items from the start of an array with array_shift in a loop, which gets slow for big arrays.

Where to use it in a project

  • Background job systems for emails, exports, image processing and reports.
  • Waiting lines in support chat, booking and ticketing apps.
  • Breadth-first search on maps, social graphs and file trees.

The solution

Keep two ends. Enqueue adds a new item at the back. Dequeue removes and returns the item at the front. Keep a front marker rather than shifting every item after each removal, and use a linked chain or a circular array so both ends are quick. Check for empty before removing.

Payoff: Before: a spike of 100 simultaneous exports crashing the server. After: jobs processed one at a time in the order they arrived.

Explain it like I am 8

A queue is the line for the school water fountain. New kids stand at the back. The kid at the front drinks first and leaves. Nobody is allowed to jump ahead, because that would not be fair.

How it works, step by step

  1. Enqueue adds a person at the back of the line.
  2. Dequeue serves and removes the person at the front.
  3. Peek looks at who is at the front without removing them.
  4. Keep both ends in mind. The front moves forward as people leave and the back grows as people arrive.

The code in four languages

PHP

<?php
class Queue {
    private array $items = [];
    private int $head = 0;                  // index of the front person
    private int $tail = 0;                  // where the next person joins

    public function enqueue($x): void { $this->items[$this->tail++] = $x; }

    public function dequeue() {
        if ($this->isEmpty()) return null;
        $x = $this->items[$this->head];
        unset($this->items[$this->head++]); // move the front forward: O(1)
        return $x;
    }
    public function peek()    { return $this->items[$this->head] ?? null; }
    public function isEmpty(): bool { return $this->head === $this->tail; }
}
// PHP ships one too: new SplQueue();  ->enqueue() / ->dequeue()

$line = new Queue();
foreach (['Asha', 'Ben', 'Chitra'] as $name) $line->enqueue($name);   // Asha arrived first
echo $line->dequeue(), "\n";                        // Asha: first in, first out
echo $line->peek(), "\n";                           // Ben is next
$line->dequeue();
echo $line->dequeue(), "\n";                        // Chitra
echo $line->isEmpty() ? 'empty' : 'not empty', "\n";   // empty

JavaScript

class Queue {
  constructor() { this.items = {}; this.head = 0; this.tail = 0; }

  enqueue(x) { this.items[this.tail++] = x; }          // join at the back

  dequeue() {
    if (this.isEmpty()) return undefined;
    const x = this.items[this.head];
    delete this.items[this.head++];                    // move the front forward: O(1)
    return x;
  }
  peek()    { return this.items[this.head]; }
  isEmpty() { return this.tail === this.head; }
}
// Beware: array.shift() works but is O(n), as everyone shuffles forward.

const line = new Queue();
for (const name of ['Asha', 'Ben', 'Chitra']) line.enqueue(name);   // Asha arrived first
console.log(line.dequeue());                                       // Asha: first in, first out
console.log(line.peek());                                          // Ben is next
line.dequeue();
console.log(line.dequeue());                                       // Chitra
console.log(line.isEmpty() ? 'empty' : 'not empty');               // empty

Java

import java.util.*;

public class Main {
    static class Queue<T> {
        private final Map<Integer, T> items = new HashMap<>();
        private int head = 0;                   // index of the front person
        private int tail = 0;                   // where the next person joins

        void enqueue(T x) { items.put(tail++, x); }              // join at the back

        T dequeue() {
            if (isEmpty()) return null;
            return items.remove(head++);        // move the front forward: O(1)
        }

        T peek() { return items.get(head); }
        boolean isEmpty() { return head == tail; }
    }
    // Java ships one too: new ArrayDeque<>() with offer() / poll().

    public static void main(String[] args) {
        Queue<String> line = new Queue<>();
        line.enqueue("Asha");
        line.enqueue("Ben");
        line.enqueue("Chitra");
        System.out.println(line.dequeue());     // Asha  (first in, first out)
        System.out.println(line.peek());        // Ben
        System.out.println(line.isEmpty());     // false
    }
}

Go

package main

import "fmt"

type Queue[T any] struct {
	items map[int]T
	head  int // index of the front person
	tail  int // where the next person joins
}

func NewQueue[T any]() *Queue[T] { return &Queue[T]{items: map[int]T{}} }

func (q *Queue[T]) Enqueue(x T) { // join at the back
	q.items[q.tail] = x
	q.tail++
}

func (q *Queue[T]) Dequeue() (T, bool) {
	var zero T
	if q.IsEmpty() {
		return zero, false
	}
	x := q.items[q.head]
	delete(q.items, q.head) // move the front forward: O(1)
	q.head++
	return x, true
}

func (q *Queue[T]) Peek() (T, bool) {
	x, ok := q.items[q.head]
	return x, ok
}

func (q *Queue[T]) IsEmpty() bool { return q.head == q.tail }

// Beware: slicing items = items[1:] works too, but a map keeps the idea explicit.

func main() {
	line := NewQueue[string]()
	line.Enqueue("Asha")
	line.Enqueue("Ben")
	line.Enqueue("Chitra")
	first, _ := line.Dequeue()
	fmt.Println(first) // Asha  (first in, first out)
	next, _ := line.Peek()
	fmt.Println(next)           // Ben
	fmt.Println(line.IsEmpty()) // false
}

Time: O(1) enqueue · O(1) dequeue · Extra space: O(n). Use a head index (or a linked list) so serving the front never shuffles everyone else.

Watch out for

  • Using array_shift() / .shift() in a hot loop. It re-indexes the entire array on every call.
  • Dequeuing from an empty queue without checking first.

Quick check

  1. Who is served first in a queue?
    • The newest arrival
    • The longest-waiting person
    • The tallest person
  2. Which pair names the two basic queue actions?
    • push / pop
    • enqueue / dequeue
    • insert / sort
  3. Which real tool is a queue?
    • Browser back button
    • Laravel job queue
    • Undo in an editor