LeetCode 622: Design Circular Queue Solution
Master LeetCode problem 622 (Design Circular Queue), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
622. Design Circular Queue
Problem Explanation
Explanation
To implement a circular queue, we can use an array to store the elements and two pointers to keep track of the front and rear of the queue. We will also need a variable to keep track of the number of elements in the queue.
The key operations are:
- enQueue: Insert an element at the rear end of the queue.
- deQueue: Delete an element from the front end of the queue.
- Front: Get the element at the front of the queue.
- Rear: Get the element at the rear of the queue.
- isEmpty: Check if the queue is empty.
- isFull: Check if the queue is full.
We will use the following formulae to update the front and rear pointers in a circular manner:
- For enQueue operation: rear = (rear + 1) % k
- For deQueue operation: front = (front + 1) % k
Time Complexity:
- enQueue, deQueue, Front, Rear, isEmpty, isFull: O(1)
Space Complexity: O(k) where k is the size of the circular queue.
Solution Code
class MyCircularQueue {
private int[] data;
private int front;
private int rear;
private int size;
public MyCircularQueue(int k) {
data = new int[k];
front = -1;
rear = -1;
size = k;
}
public boolean enQueue(int value) {
if (isFull()) {
return false;
}
if (isEmpty()) {
front = 0;
}
rear = (rear + 1) % size;
data[rear] = value;
return true;
}
public boolean deQueue() {
if (isEmpty()) {
return false;
}
if (front == rear) {
front = -1;
rear = -1;
return true;
}
front = (front + 1) % size;
return true;
}
public int Front() {
if (isEmpty()) {
return -1;
}
return data[front];
}
public int Rear() {
if (isEmpty()) {
return -1;
}
return data[rear];
}
public boolean isEmpty() {
return front == -1;
}
public boolean isFull() {
return (rear + 1) % size == front;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 622 (Design Circular Queue)?
This page provides optimized solutions for LeetCode problem 622 (Design Circular Queue) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 622 (Design Circular Queue)?
The time complexity for LeetCode 622 (Design Circular Queue) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 622 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 622 in Java, C++, or Python.