In Queue insertions happen at one end, but removals happen from the other end. So the array implementation is not going to be straightforward like stack where we insert and remove from the end.
- In the simple implementation, we insert at the end and remove from the beginning. So the time complexity of insert is O(1), but removal becomes O(n). If we do the other way that insert at the beginning and remove from the end, then insertion operation becomes O(n).
- To make both insertion and removal O(1), we use circular array implementation. We change front and rear in modular fashion, so that we maintain starting and ending positions of the current chunk of array where queue elements are stored.
Simple Array implementation
For implementing the queue, we only need to keep track of two variables: front and size. We can find the rear as front + size - 1.
- The Enqueue operation is simple, we simply insert at the end of the array. This operation takes O(1) time
- The Dequeue operation is costly as we need remove from the beginning of the array. To remove an item, we need to move all items one position back. Hence this operations takes O(n) time.
- If we do otherwise that insert at the begin and delete from the end, then insert would become costly.
Please refer Simple Array implementation of Queue for implementation.
| Operations | Complexity |
|---|---|
| Enqueue (insertion) | O(1) |
| Deque (deletion) | O(n) |
| Front (Get front) | O(1) |
| Rear (Get Rear) | O(1) |
| IsFull (Check queue is full or not) | O(1) |
| IsEmpty (Check queue is empty or not) | O(1) |
Circular Array Implementation
We can make all operations in O(1) time using circular array implementation.
- The idea is to treat the array as a circular buffer. We move front and rear using modular arithmetic
- When we insert an item, we increment front using modular arithmetic (which might leave some free space at the beginning of the array).
- When we delete an item, we decrement rear using modular arithmetic.
Please refer Circular Array implementation Of Queue for details of implementation
| Operations | Complexity |
|---|---|
| Enqueue (insertion) | O(1) |
| Deque (deletion) | O(1) |
| Front (Get front) | O(1) |
| Rear (Get Rear) | O(1) |
| IsFull (Check queue is full or not) | O(1) |
| IsEmpty (Check queue is empty or not) | O(1) |