Design a circular queue

A fixed-size queue backed by one array, where the head wraps around with modulo instead of ever shifting elements.

Time O(1) per operationSpace O(n)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A normal queue shifts every element left after a dequeue, or wastes growing space. A circular queue instead keeps a fixed array and lets the logical front, head, walk forward and wrap back to index 0 with modulo. The item at (head + count) % capacity is always the next free slot, so enqueue, dequeue and front are all O(1) with no data ever moved.

Code

public class MyCircularQueue {
    readonly int[] buf;
    int head = 0, count = 0;

    public MyCircularQueue(int capacity) => buf = new int[capacity];

    public bool Enqueue(int x) {
        if (count == buf.Length) return false;
        buf[(head + count) % buf.Length] = x;
        count++;
        return true;
    }

    public bool Dequeue() {
        if (count == 0) return false;
        head = (head + 1) % buf.Length;
        count--;
        return true;
    }

    public int Front() => count == 0 ? -1 : buf[head];
}

Tips

In the .NET library

.NET already has Queue<T> as a circular buffer under the hood with amortised O(1) Enqueue/Dequeue; this lesson builds the same idea by hand with a fixed capacity.