Data Structures · Visualization
Circular Queue: Enqueue
Circular Queue
Adding an element to a circular queue advances the rear index modulo the capacity, so it wraps back to the start when it reaches the array's end, as long as the queue isn't already full. Time: O(1). Space: O(1) extra.
Big-O: enqueue / dequeue both O(1) via wrap-around indices on a fixed array.
Circular Queue: Enqueue
Circular QueueAdding an element to a circular queue advances the rear index modulo the capacity, so it wraps back to the start when it reaches the array's end, as long as the queue isn't already full.
How Enqueue Works
- Check if the queue is full (size === capacity); if so, reject or resize.
- Compute the next rear position: rear = (rear + 1) % capacity.
- Store the new element at index rear.
- Increment size by 1.
Enqueue Worked Example
Input: Capacity 4, current [_,20,30,40] front=1 rear=3 size=3, enqueue 60
- size(3) !== capacity(4), so proceed
- rear = (3+1) % 4 = 0
- array[0] = 60
- size becomes 4 (now full)
Output: [60,20,30,40], front=1, rear=0, size=4
Press ▶ Run to watch it step by step.
# enqueue: store at tail, then advance tail mod size
def enqueue(q, tail, size, cap, v):
if size == cap:
raise RuntimeError("full")
q[tail] = v
tail = (tail + 1) % cap
return tail, size + 1
# q = [None]*4; tail, size = 0, 0
# tail, size = enqueue(q, tail, size, 4, 3)
# example: enqueue 60 on [20, 30, 40]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Enqueue Time & Space Complexity
When to Use Enqueue
- Producer side of producer-consumer buffers
- Adding events to a fixed-size event ring
- Network packet buffering
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.