fixed-size queue
data structure
queue operations
memory management
element removal

Is there a fixed sized queue which removes excessive elements?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

In computer science and programming, a queue is a fundamental data structure that follows the First-In-First-Out (FIFO) principle. Elements are added at one end, called the "rear," and removed from the other end, known as the "front." However, when handling dynamic data or in scenarios needing constant control over resource usage, a fixed-size queue can be advantageous. Such queues automatically remove or discard excessive elements that exceed their predefined capacity.

Understanding Fixed-Size Queues

A fixed-size queue, also known as a bounded queue, is particularly useful for applications where memory usage constraints are critical. While like a regular queue, it enforces a maximum number of elements it can hold. Once this capacity is reached, any new element added typically causes the removal of an element from the opposite end of where elements are added, maintaining queue capacity.

Key Characteristics

  • Bounded Capacity: The total number of elements that the queue can hold is limited.
  • Automatic Removal: When the queue exceeds its capacity, one or more elements are automatically removed.
  • FIFO Order: In most implementations, the oldest (earliest pasted) element is removed first.

Technical Implementation

Circular Buffer Approach

A common implementation of a fixed-size queue is using a circular buffer (or ring buffer). This approach efficiently manages memory by reusing the previously occupied space once it's freed. Here's a simplified example in Python to demonstrate this concept:

python
1class FixedSizeQueue:
2    def __init__(self, capacity):
3        self.capacity = capacity
4        self.queue = [None] * capacity
5        self.front = 0
6        self.rear = -1
7        self.size = 0
8
9    def enqueue(self, item):
10        if self.size == self.capacity:
11            self.front = (self.front + 1) % self.capacity
12        
13        self.rear = (self.rear + 1) % self.capacity
14        self.queue[self.rear] = item
15        self.size = min(self.size + 1, self.capacity)
16
17    def dequeue(self):
18        if self.size == 0:
19            raise IndexError("Queue is empty")
20            
21        item = self.queue[self.front]
22        self.front = (self.front + 1) % self.capacity
23        self.size -= 1
24        return item
25
26    def __str__(self):
27        return 'Queue: ' + str([self.queue[(self.front + i) % self.capacity] for i in range(self.size)])
28
29# Example usage
30fsq = FixedSizeQueue(3)
31fsq.enqueue('a')
32fsq.enqueue('b')
33fsq.enqueue('c')
34fsq.enqueue('d')  # 'a' will be removed to make space for 'd'
35print(fsq)

In the example above, the FixedSizeQueue class utilizes a list to store elements and manages insertion and removal via index manipulation. It maintains the current size and updates indices for front and rear positions circularly.

Considerations in Caching

Fixed-size queues are frequently used in caching, particularly in Least Recently Used (LRU) Cache algorithms. Here, when the cache becomes full, the cache removes the least recently used items to make space for new data. This model fits perfectly on a fixed-size queue’s mechanics of eviction.

Applications

  1. Networking: Managing network traffic, handling a fixed-size packet queue to avoid buffer overflow and manage congestion.
  2. Multitasking Systems: Scheduling tasks where limited buffer space requires timely processing and eviction of tasks.
  3. Audio/Video Processing: Buffering a stream of audio or video frames to smooth out data flow discrepancies.
  4. Telemetry Data: Storing recent telemetry data where only a certain history is retained and old data is discarded when new data arrives.
  5. Logging Systems: Fixed-size logs where only recent entries are relevant and older logs automatically expire.

Comparison Table

Here's a summary comparing fixed-size queues with other queue types:

AspectFixed-Size QueueDynamic QueuePriority Queue
Memory ConsumptionConstant, known sizeDynamic, grows/shrinksVaries based on requirements and priority levels
Element Removal StrategyAutomatic oldest removalManual removal based on usageRemoves based on priority not strictly FIFO
Application ScenariosResource-limited systems, real-time processingFlexible use-casesScheduling tasks with priorities
Complexity of ImplementationModerateSimpleComplex ordering mechanism

Conclusion

A fixed-size queue is a strategic data structure choice, especially when memory constraints or predictable performance metrics are priorities. By limiting the number of stored elements, such a queue enforces resource control while maintaining efficient access and removal properties. Understanding its implementation using structures like circular buffers provides valuable insights into effective queue management strategies for various applications across software development.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.