Queue Implementation Using Array
The simplest way to build a queue is to back it with an array and track a front index and a rear index. As long as those two indices are updated correctly on every enqueue and dequeue, the array behaves like a proper FIFO queue.
Implementation Steps
- Initialize an array of fixed size (for static implementation) or dynamic array
- Initialize two pointers: front (for dequeue) and rear (for enqueue), both set to -1 initially
- Implement boundary checks for overflow (full queue) and underflow (empty queue) conditions
- For circular queue implementation, use modulo arithmetic for pointer updates
Enqueue Algorithm
- Check if queue is full (if (rear == capacity - 1) for linear array)
- For empty queue, set both front and rear to 0
- For circular queue: rear = (rear + 1) % capacity
- Insert new element at items[rear]
- Increment size counter
Dequeue Algorithm
- Check if queue is empty (front == -1)
- Store the front element to return later
- If only one element (front == rear), reset pointers to -1
- For circular queue: front = (front + 1) % capacity
- Decrement size counter
- Return the stored element
Time & Space Complexity
- Enqueue Operation: O(1) - Amortized constant time for dynamic arrays
- Dequeue Operation: O(1) - No shifting needed with pointer approach
- Peek Operation: O(1) - Direct access via front pointer
- Space Usage: O(n) - Linear space for storing elements
Advertisement
Pros and Cons
- Pros: Simple implementation, cache-friendly (array elements contiguous in memory)
- Pros: Efficient O(1) operations with pointer tracking
- Cons: Fixed size limitation in static array implementation
- Cons: Wasted space in linear array implementation without circular approach
Practical Considerations
The catch with a plain array is wasted space at the front once you've dequeued a few elements — the circular-array trick fixes that by letting the rear index wrap back around to index 0 once it hits the end.
Queues are widely used in scenarios like printer job scheduling, call center systems, and network packet handling where order preservation is crucial.