Implement Queue using Arrays
EasyA circular buffer with two indices
Problem
Implement a queue (enqueue, dequeue, front) using an array (circular buffer).
A line at a shop: join at the back, leave from the front.
The idea
Hold a front and a rear index and wrap both around with modulo, so dequeuing does not shift the whole array. Tracking the size separately is what lets you distinguish a full buffer from an empty one, since both leave the indices equal.
The trick
- Wrap with `(i + 1) % capacity`.
- Keep an explicit size or leave one slot empty; otherwise full and empty look identical.
- Every operation is O(1).
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — enqueue 1,2; dequeue Values: 1, 2.
1use front, rear indices modulo capacity2enqueue: arr[rear]=x; rear=(rear+1)%cap3dequeue: x=arr[front]; front=(front+1)%capInput
- array
- [1, 2]
Output
- answer
- —
Check yourself
2 quick questions about this walkthrough. A wrong answer costs nothing.
Example
- Input:
- enqueue 1,2; dequeue
- Output:
- returns 1
Practice this problem:GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.