Data Structures · Visualization
Implement Queue (Array)
Queue
A queue can be built on top of an array by tracking two indices: one for the front and one for the back. Time: O(1) with a circular buffer or front index; O(n) if naively shifting after each dequeue. Space: O(n).
Big-O: enqueue / dequeue are both O(1).
Implement Queue (Array)
QueueA queue can be built on top of an array by tracking two indices: one for the front and one for the back. A naive approach removes from index 0 and shifts everything left (slow); a smarter approach uses a 'circular buffer' where the front index simply advances, avoiding costly shifts.
How Implement Queue (Array) Works
- Use an array plus a front index and a back index (or count).
- Enqueue: place the new value at the back index, then advance the back index.
- Dequeue: read the value at the front index, then advance the front index (without shifting other elements).
- In a circular implementation, wrap indices back to 0 when they reach the array's end.
Implement Queue (Array) Worked Example
Input: Array-backed queue: enqueue(5), enqueue(8), dequeue()
- enqueue(5) → array: [5], front=0, back=1
- enqueue(8) → array: [5, 8], back=2
- dequeue() → read index front(0)=5, advance front to 1
Output: Dequeued: 5, queue now conceptually: [8]
Press ▶ Run to watch it step by step.
# Queue: FIFO, deque-backed
from collections import deque
q = deque()
q.append(1) # enqueue
q.append(2)
front = q[0] # peek
q.popleft() # dequeue
# All operations are O(1)
# example: queue 5 on [1, 2, 3]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.
Implement Queue (Array) Time & Space Complexity
When to Use Implement Queue (Array)
- Simple, fixed-capacity task or message queues
- Ring buffers used in streaming and networking code
- Any FIFO structure with a known maximum size
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.