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)

Queue

A 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

  1. Use an array plus a front index and a back index (or count).
  2. Enqueue: place the new value at the back index, then advance the back index.
  3. Dequeue: read the value at the front index, then advance the front index (without shifting other elements).
  4. 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()

  1. enqueue(5) → array: [5], front=0, back=1
  2. enqueue(8) → array: [5, 8], back=2
  3. dequeue() → read index front(0)=5, advance front to 1

Output: Dequeued: 5, queue now conceptually: [8]

Try your own input
bottom
1
2
3
← top
Active / highlighted Min stack Result

Press ▶ Run to watch it step by step.
Python · Stacks & Queues in Code
# 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]
Input: Array-backed queue: enqueue(5), enqueue(8), dequeue()

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

TimeO(1) with a circular buffer or front index; O(n) if naively shifting after each dequeue
SpaceO(n)

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Ready for the next step?

See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.