Problem Link - Implement CircularQueue using Array
Problem Statement
You are tasked with implementing a circular queue using an array. A circular queue allows for efficient use of space by reusing the empty slots that are created when elements are dequeued. Your implementation should support the following operations:
-
Enqueue: Add an element to the rear of the queue.
-
Dequeue: Remove an element from the front of the queue.
-
Display: Print all elements in the queue.
-
Exit: Terminate the program.
Approach
-
Full and Empty Checks:
-
isFull: The queue is full if
front == (rear + 1) % capacity
, meaning no space is left. -
isEmpty: The queue is empty if
front == -1
, indicating no elements.
-
-
Enqueue:
-
Check if the queue is full using
isFull
. If full, no element can be added. -
If empty, set
front
andrear
to 0. -
Otherwise, increment
rear
circularly using(rear + 1) % capacity
and insert the new value.
-
-
Dequeue:
-
Check if the queue is empty using
isEmpty
. If empty, no element can be removed. -
Retrieve the element at
front
, then incrementfront
circularly using
(front + 1) % capacity
. -
If the queue becomes empty (
front == rear
), resetfront
andrear
to -1.
-
-
Display:
-
If the queue is empty, print a message.
-
Otherwise, traverse and print the elements from
front
torear
circularly.
-
Time Complexity
-
Enqueue/Dequeue/Is Full/Is Empty: O(1) - Constant time operations.
-
Display: O(n) - Linear time to display all elements.
Space Complexity
- O(capacity) - Linear space, as we use a fixed-size array to store elements.