AlgoTales · Roadmap

Circular queue

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A circular queue is a queue stored in a fixed-size ring. When the end of the array is reached, new items wrap around to the free space at the beginning, so memory is reused and nothing needs to be shifted.

Practical use cases

  • Web app: Keep only the last 100 log lines. A live-log page on an admin dashboard displays the latest 100 messages. New messages overwrite the oldest slot in a fixed ring, so memory never grows and nothing is shifted. The page can run for weeks without slowing down or eating more memory, however many messages the servers produce.
  • Web app: Recent searches or last viewed products. A shop remembers the last 10 products a visitor viewed. When the eleventh arrives, it replaces the oldest in the ring. The code is tiny, uses a fixed amount of memory, and the "recently viewed" strip always shows the latest ten.
  • System: Audio, video and network buffers. Sound cards, video streams and network cards hold incoming data in ring buffers. A producer writes at one point and a consumer reads at another, both chasing each other around the ring, so the data flows smoothly with no copying.

The story: The Never-Ending Hook Board

At the Diwali mela, old Mr. Iyer ran the cycle-parking stall. He gave every cyclist a token and hung the bike keys on a long wooden board with five hooks in a row. First come, first served: the key at the left always went back first.

The trouble began after a few hours. Hooks 0, 1 and 2 were empty because those cyclists had left, but new customers kept being sent to hooks 3 and 4, and then there was no place left on the board. Mr. Iyer started shifting every key one hook to the left each time someone left. His arms ached and the queue grew.

His granddaughter Mira rolled her eyes. "Dadaji, bend the board into a circle. When you reach the last hook, just go back to the first. Those empty hooks are waiting for you!" Now two small paper flags did the whole job: a head flag for the next key to return and a tail flag for the next free hook. When a flag reached hook 4, it hopped back to hook 0. That bendy board is a circular queue, also known as a ring buffer.

How to spot this problem, and where you need it

You need a queue or a "last N items" list with a fixed memory size, and shifting items or growing arrays forever would waste time and memory.

Signs you need it

  • The requirement says "keep only the last N", "buffer", "rolling window" or "overwrite the oldest".
  • Your list keeps growing and you periodically trim it with array_slice or array_shift, causing small pauses.
  • A writer and a reader operate at different speeds, such as incoming data and a slower processor.

Where to use it in a project

  • Recent-activity strips, last-N logs and recent-search lists in web apps.
  • Buffers between a fast producer and a slower consumer, such as streaming or uploads.
  • Fixed-memory embedded or real-time code, such as audio players and device firmware.

The solution

Allocate an array of fixed size and two markers: front (where to read) and rear (where to write). When a marker passes the last slot, it wraps to slot zero using remainder arithmetic. Track the count to tell full from empty. If full, either refuse the new item or overwrite the oldest, depending on what you need.

Payoff: Before: an array growing without limit and being trimmed constantly. After: a fixed block of memory with constant work per item.

Explain it like I am 8

Imagine kids sitting on a round merry-go-round with a fixed number of seats. When one kid gets off, the next newcomer takes that empty seat instead of everyone shuffling around. The end of the line is glued to the beginning.

How it works, step by step

  1. Make a fixed-size array (the ring) and keep two things: head (where the next removal happens) and size (how many items are inside).
  2. Enqueue: if size equals the capacity, the queue is full. Otherwise write at slot (head + size) % capacity and add one to size.
  3. Dequeue: if size is 0, the queue is empty. Otherwise read the slot at head, then move head to (head + 1) % capacity and subtract one from size.
  4. The % sign is the "wrap round" trick: after the last slot, the count starts again from slot 0, just like clock hands going from 12 back to 1.
  5. Nothing ever shifts, so both operations are instant.

The code in four languages

PHP

<?php
class CircularQueue {
    private array $slots;
    private int $head = 0;   // index of the next item to remove
    private int $size = 0;   // how many items are stored

    public function __construct(private int $capacity) {
        $this->slots = array_fill(0, $capacity, null);
    }
    public function enqueue($item): bool {
        if ($this->size === $this->capacity) return false;          // full
        $tail = ($this->head + $this->size) % $this->capacity;      // wrap round
        $this->slots[$tail] = $item;
        $this->size++;
        return true;
    }
    public function dequeue() {
        if ($this->size === 0) return null;                         // empty
        $item = $this->slots[$this->head];
        $this->slots[$this->head] = null;
        $this->head = ($this->head + 1) % $this->capacity;          // wrap round
        $this->size--;
        return $item;
    }
}

$q = new CircularQueue(3);
foreach (['A', 'B', 'C', 'D'] as $x) {
    echo "enqueue $x: " . ($q->enqueue($x) ? 'ok' : 'full') . "\n";   // D is rejected
}
echo "dequeue: " . $q->dequeue() . "\n";    // A
echo "enqueue D: " . ($q->enqueue('D') ? 'ok' : 'full') . "\n";  // D lands in A's old slot
echo "dequeue: " . $q->dequeue() . "\n";    // B
echo "dequeue: " . $q->dequeue() . "\n";    // C
echo "dequeue: " . $q->dequeue() . "\n";    // D

JavaScript

class CircularQueue {
  constructor(capacity) {
    this.capacity = capacity;
    this.slots = new Array(capacity).fill(null);
    this.head = 0;   // index of the next item to remove
    this.size = 0;   // how many items are stored
  }
  enqueue(item) {
    if (this.size === this.capacity) return false;            // full
    const tail = (this.head + this.size) % this.capacity;     // wrap round
    this.slots[tail] = item;
    this.size++;
    return true;
  }
  dequeue() {
    if (this.size === 0) return null;                         // empty
    const item = this.slots[this.head];
    this.slots[this.head] = null;
    this.head = (this.head + 1) % this.capacity;              // wrap round
    this.size--;
    return item;
  }
}

const q = new CircularQueue(3);
for (const x of ['A', 'B', 'C', 'D']) {
  console.log('enqueue ' + x + ': ' + (q.enqueue(x) ? 'ok' : 'full'));   // D is rejected
}
console.log('dequeue: ' + q.dequeue());    // A
console.log('enqueue D: ' + (q.enqueue('D') ? 'ok' : 'full'));          // D lands in A's old slot
console.log('dequeue: ' + q.dequeue());    // B
console.log('dequeue: ' + q.dequeue());    // C
console.log('dequeue: ' + q.dequeue());    // D

Java

public class Main {
    static class CircularQueue {
        private final String[] slots;
        private final int capacity;
        private int head = 0;    // index of the next item to remove
        private int size = 0;    // how many items are stored

        CircularQueue(int capacity) {
            this.capacity = capacity;
            this.slots = new String[capacity];
        }

        boolean enqueue(String item) {
            if (size == capacity) return false;                  // full
            int tail = (head + size) % capacity;                 // wrap round
            slots[tail] = item;
            size++;
            return true;
        }

        String dequeue() {
            if (size == 0) return null;                          // empty
            String item = slots[head];
            slots[head] = null;
            head = (head + 1) % capacity;                        // wrap round
            size--;
            return item;
        }
    }

    public static void main(String[] args) {
        CircularQueue q = new CircularQueue(3);
        for (String x : new String[]{"A", "B", "C", "D"}) {
            System.out.println("enqueue " + x + ": " + (q.enqueue(x) ? "ok" : "full"));   // D is rejected
        }
        System.out.println("dequeue: " + q.dequeue());    // A
        System.out.println("enqueue D: " + (q.enqueue("D") ? "ok" : "full"));            // D lands in A's old slot
        System.out.println("dequeue: " + q.dequeue());    // B
        System.out.println("dequeue: " + q.dequeue());    // C
        System.out.println("dequeue: " + q.dequeue());    // D
    }
}

Go

package main

import "fmt"

type CircularQueue struct {
	slots []string
	head  int // index of the next item to remove
	size  int // how many items are stored
}

func NewCircularQueue(capacity int) *CircularQueue {
	return &CircularQueue{slots: make([]string, capacity)}
}

func (q *CircularQueue) Enqueue(item string) bool {
	if q.size == len(q.slots) { // full
		return false
	}
	tail := (q.head + q.size) % len(q.slots) // wrap round
	q.slots[tail] = item
	q.size++
	return true
}

func (q *CircularQueue) Dequeue() (string, bool) {
	if q.size == 0 { // empty
		return "", false
	}
	item := q.slots[q.head]
	q.slots[q.head] = ""
	q.head = (q.head + 1) % len(q.slots) // wrap round
	q.size--
	return item, true
}

func okFull(ok bool) string {
	if ok {
		return "ok"
	}
	return "full"
}

func main() {
	q := NewCircularQueue(3)
	for _, x := range []string{"A", "B", "C", "D"} {
		fmt.Println("enqueue "+x+":", okFull(q.Enqueue(x))) // D is rejected
	}
	item, _ := q.Dequeue()
	fmt.Println("dequeue:", item)                     // A
	fmt.Println("enqueue D:", okFull(q.Enqueue("D"))) // D lands in A's old slot
	for i := 0; i < 3; i++ {
		item, _ := q.Dequeue()
		fmt.Println("dequeue:", item) // B, C, D
	}
}

Time: O(1) · Extra space: O(n). Every enqueue and dequeue touches one slot and moves one flag; the ring has a fixed size n that never grows.

Watch out for

  • Forgetting the wrap with %, so the tail runs off the end of the array while earlier slots sit empty.
  • Using only head and tail without a size: then "full" and "empty" look identical (head equals tail in both cases).
  • Silently overwriting the oldest item when full without meaning to. Decide: reject the newcomer or overwrite on purpose.

Quick check

  1. What problem does a circular queue fix compared with a simple array queue?
    • Free slots at the front are reused instead of wasted
    • It sorts the items
    • It lets you remove from the middle
  2. Capacity is 5, head is 3 and size is 4. Where does the next item go?
    • Slot 4
    • Slot 2
    • Slot 0
  3. What is the time cost of enqueue and dequeue?
    • O(n) because items shift
    • O(log n)
    • O(1)