Queue Implementation Using Array
Implementing a Queue using an array is a fundamental approach where we use a fixed-size or dynamic array to store elements while maintaining FIFO order. The array implementation requires careful handling of front and rear pointers to efficiently enqueue and dequeue elements.
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
Basic Class Structure
class Queue { constructor(capacity) { this.items = new Array(capacity); this.capacity = capacity; this.front = -1; this.rear = -1; this.size = 0; } // Check if queue is full isFull() { return this.size === this.capacity; } // Check if queue is empty isEmpty() { return this.size === 0; }
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
Circular Array Note: The modulo operation (% capacity
) enables the circular behavior by wrapping the pointer to the start when it reaches the end.
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
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
In a circular array implementation, we treat the array as circular to maximize space utilization. When either pointer reaches the end of the array, it wraps around to the beginning.
Queues are widely used in scenarios like printer job scheduling, call center systems, and network packet handling where order preservation is crucial.