Queue
1if rear == capacity − 1: overflow (no room at the back)2rear ← rear + 13a[rear] ← v
What is a Queue?
A queue works like a line of people: new items join at the rear and items leave from the front. Whatever went in first comes out first, which is called FIFO: first in, first out.
The visualizer shows the simplest array version, with two indexes. rear moves right when you enqueue and front moves right when you dequeue. Dequeue a few values and keep enqueueing: the slots behind front are never used again, so the queue reports "full" while empty slots are still sitting at the front. The circular queue solves exactly this.
Join at the rear, leave from the front.
How the Operations Work
Enqueue
If rear is not at the last slot, move it one step right and store the value there. Otherwise the queue overflows.
Dequeue
If the queue isn't empty (front ≤ rear), read a[front] and move front one step right.
Peek
Look at the front value without removing it.
The wasted-space problem
Shifting every item left after each dequeue would fix it but costs O(n). Wrapping the indexes round to the start (a circular queue) fixes it in O(1).
Implementation
Properties & Complexity
Time Complexity
- • Enqueue: O(1)
- • Dequeue: O(1)
- • Peek: O(1)
- • Search for a value: O(n)
Space & Properties
- • Space: O(n)
- • Order: FIFO
- • Simple array: wastes slots at the front
- • Fix: circular queue or a linked list
Where Queues Are Used
- • Breadth-first search: visit nodes level by level
- • Printing / task queues: jobs run in arrival order
- • Buffers: keyboard input, network packets, streaming
- • Scheduling: waiting lines for a shared resource
Limitations
- • Wasted slots: the simple array version can't reuse the front
- • No random access: only the front can be read
- • Fixed size: the array version can overflow