MrainW's Home

All things come to those who wait!

0%

LeetCode 622. Design Circular Queue

Question

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called “Ring Buffer”.

One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.

https://leetcode.com/problems/design-circular-queue/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class MyCircularQueue {
int[] q;
int front, rear, size;
public MyCircularQueue(int k) {
front = 0;
rear = -1;
q = new int[k];
}

public boolean enQueue(int value) {
if(!isFull()){
rear=(rear + 1) % q.length;
q[rear] = value;
size++;
return true;
} else return false;
}

public boolean deQueue() {
if(!isEmpty()){
front = (front + 1) % q.length;
size--;
return true;
} else return false;
}

public int Front() {
return isEmpty() ? -1 : q[front];
}

public int Rear() {
return isEmpty() ? -1 : q[rear];
}

public boolean isEmpty() {
return size == 0;
}

public boolean isFull() {
return size == q.length;
}
}

Complexity: O(1)

Space complexity: O(k)

Welcome to my other publishing channels