Explain the concept of a queue as a "first in, first out" (FIFO) data structure
A queue is a linear data structure where elements are added at the rear (back) and removed from the front . The first element added is the first one to be…
FIFO — First In, First Out
A queue is a linear data structure where elements are added at the rear (back) and removed from the front. The first element added is the first one to be removed — like a line at a ticket counter.
Core Operations
| Operation | Action |
|---|---|
| Enqueue | Add an element to the rear of the queue |
| Dequeue | Remove an element from the front of the queue |
| Front | View the element at the front without removing it |
| Rear | View the element at the rear without removing it |
| isEmpty() | Check if the queue has any elements |
| isFull() | Check if the queue has reached its maximum capacity |
Error Conditions
| Condition | Meaning |
|---|---|
| Overflow | Attempting to Enqueue when the queue is full |
| Underflow | Attempting to Dequeue from an empty queue |
Implementation in Python
from collections import deque
queue = deque()
# Enqueue
queue.append("A") # queue = ['A']
queue.append("B") # queue = ['A', 'B']
queue.append("C") # queue = ['A', 'B', 'C']
# Front and Rear
print(queue[0]) # 'A' — front
print(queue[-1]) # 'C' — rear
# Dequeue
queue.popleft() # removes 'A' — first in, first out
Applications of Queues
| Application | How it uses a queue |
|---|---|
| Banking — Ticket counter | Customers join at the rear, served from the front |
| CPU task scheduling | OS schedules processes in arrival order (FIFO) |
| IO Buffers | Buffers store data between slow devices and the CPU |
| Call centres | Incoming calls are queued and answered in order |
| Print queue | Print jobs line up and are processed in order |
| Network packet queuing | Packets wait in queues before being forwarded |
Queues in Asynchronous I/O
Queues are essential in asynchronous I/O, where data is being produced faster than it can be consumed — the queue acts as a buffer to prevent data loss.
Real-world example — downloading a large file:
Server → Network Buffer (queue) → Program processing
Fast Slow
If the server must wait for the program to finish processing each chunk before sending the next → the network sits idle and throughput drops.
If the server sends each chunk into a queue and immediately continues → both sides run independently, maximizing efficiency. The producer (server) never blocks, and the consumer (program) processes at its own pace.