Design a Circular Queue

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-03-18

Problem Statement

A queue is a linear data structure that follows FIFO (First In First Out). A circular queue overcomes the limitation of a normal queue by reusing empty slots after elements are dequeued — making it more space efficient.


Your task is to design and implement a circular queue that supports standard queue operations.


✅ Functional Requirements:

1.<span></span>Initialization
2.<span></span>The queue should be initialized with a fixed capacity N.
3.<span></span>Enqueue (insert)
4.<span></span>Add an element at the rear of the queue.
5.<span></span>If the queue is full, the operation should fail.
6.<span></span>Dequeue (remove)
7.<span></span>Remove an element from the front of the queue.
8.<span></span>If the queue is empty, the operation should fail.
9.<span></span>Front / Rear Peek
10.<span></span>Retrieve (but not remove) the front element.
11.<span></span>Retrieve (but not remove) the rear element.
12.<span></span>isEmpty / isFull
13.<span></span>Check whether the queue is empty or full.


⚙️ Constraints:

1.<span></span>The queue size is fixed and known at initialization.
2.<span></span>Operations must run in O(1) time.
3.<span></span>Use constant extra space (apart from the queue array).
4.<span></span>Handle wrap-around correctly when front/rear pointers reach the end.


🧪 Example Scenario:

<div><div><br /></div><div>Initialize circular queue with capacity = 3</div><div>Enqueue(10) -> success</div><div>Enqueue(20) -> success</div><div>Enqueue(30) -> success</div><div>Enqueue(40) -> fail (queue full)</div><div><br /></div><div>Front() -> 10</div><div>Rear() -> 30</div><div><br /></div><div>Dequeue() -> removes 10</div><div>Enqueue(40) -> success (wrap-around, stored at index 0)</div><div><br /></div><div>Front() -> 20</div><div>Rear() -> 40</div></div>


🔧 Expectations in an LLD Round:

1.<span></span>Define the class structure (CircularQueue).
2.<span></span>Decide internal representation (array with two pointers: front, rear).
3.<span></span>Implement required methods (enqueue, dequeue, front, rear, isEmpty, isFull).
4.<span></span>Ensure correctness in wrap-around cases.


Solution

Comments