Beginner · INTERACTIVE LESSON
Queue
Enqueue at the rear, peek at the front, and dequeue the earliest value using a circular buffer.
The interactive player is loading. If it does not appear, you can still read the explanation below.
THE IDEA BEHIND THE STEPS
How it works
A queue is first in, first out (FIFO), unlike a last-in-first-out stack. Enqueue adds at the rear; dequeue removes and returns the oldest remaining value at the front; peek returns it without removing it. This data structure does not provide broker delivery, persistence or acknowledgement guarantees.
This bounded circular buffer starts empty with capacity 1–16, up to 32 operations and whole-number values -999–999. Physical slots stay fixed. Front is a cursor in 0..C-1, marking the oldest item only when size is positive. Rear is the newest occupied slot, or none when empty. Next write is (front + size) modulo C; it is blocked when full. Size distinguishes full from empty even when front equals next write. Dequeue clears the front slot and advances front modulo C; no values shift. Item IDs use enqueue operation numbers, so duplicate values remain distinct after slot reuse.
Full enqueue returns overflow; empty dequeue and peek return underflow. Rejected operations preserve slots and pointers and later operations still run. Successful enqueue returns success. Best- and worst-case enqueue, dequeue and peek take O(1) algorithm time with this fixed buffer. Allocated space is O(C) for capacity C. Shifting an array on dequeue instead takes O(k) work for k items. Snapshot copies and history add replay overhead; animation speed is not algorithm runtime.
Completed operations count includes rejected attempts. Writes count one assignment per successful enqueue and one clear per successful dequeue. Peek and rejected operations write nothing. Check steps show the prior state and result steps show the return and updated state. Every state is readable without animation, including with reduced motion.