Queue Implementation in a Fixed-Size Buffer
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-04-04
Problem Statement
Design and implement a queue data structure that operates on top of a fixed-size circular buffer (array).
Design and implement a Queue using a fixed-size circular buffer that supports O(1) enqueue and dequeue operations, handles underflow/overflow gracefully, and optionally provides thread-safety for concurrent producers and consumers.
The queue should support basic operations, be efficient in time and space, and handle edge cases gracefully.
🔶 Requirements
1.<span></span>Basic Operations
2.<span></span>enqueue(x) → Add an element to the queue.
3.<span></span>dequeue() → Remove and return the front element.
4.<span></span>peek() → Return the front element without removing it.
5.<span></span>isEmpty() → Check if the queue is empty.
6.<span></span>isFull() → Check if the queue is full.
7.<span></span>Implementation Details
8.<span></span>Must use a fixed-size buffer (array).
9.<span></span>Use circular indexing (wrap-around when end of buffer is reached).
10.<span></span>Avoid shifting elements on dequeue().
11.<span></span>Thread Safety (Optional / Advanced)
12.<span></span>Design a thread-safe version of the queue using locks or condition variables.
13.<span></span>Support multiple producers and consumers (enqueue and dequeue from different threads).
14.<span></span>Error Handling
15.<span></span>If enqueue() is called on a full queue → throw/return overflow error.
16.<span></span>If dequeue() is called on an empty queue → throw/return underflow error.
🔶 Constraints
1.<span></span>Buffer size N is fixed at initialization.
2.<span></span>Operations must run in O(1) time.
3.<span></span>Memory usage should be O(N) only.
🔶 Example Use Cases
1.<span></span>Task Scheduling → Jobs waiting in a queue before execution.
2.<span></span>Message Buffering → Network packets stored in a queue before being processed.
3.<span></span>Producer-Consumer Problem → Multiple threads producing and consuming data concurrently.
🔶 Expected Design
1.<span></span>Maintain two pointers (or indices):
2.<span></span>front → index of the first element.
3.<span></span>rear → index where the next element will be inserted.
4.<span></span>Keep track of size or use modular arithmetic to distinguish between empty and full.