design
queue
]
Leetcode 0622. Design Circular Queue
Problem statement
https://leetcode.com/problems/design-circular-queue/
Solution
The idea here is to use list of size k
and modulo arithmetic. Let self.CircQueue
be this list, fill it with -1
in the beginning and also keep two values self.front
which points one element after front element and self.end
which points at the end element. For example when we have [-1, -1, 2, 3, 4, -1
elements in our list, it means that self.end = 2
and self.front = 5
. Let us go through operations quickly:
1.enQueue
: first check if our data structure is full and if it is return False
. In opposite case decrease self.end
and put new element.
2.deQueue
: first check if our data structure is empty and if it is return False
. In opposite case decrease self.front
and remove one element, that is make it equal to -1
.
3.Front
is similar to deQueue
, but just return one element before front
.
4.Rear
is similar to enQueue
, but just return element with index end
.
5.isEmpty
just check if front
is equal to end
.
6.isFull
just check that in total we have k
elements: end - front
.
Complexity
Time complexity of all operations is O(1)
. Space complexity of total data structure is O(k)
.
Code
class MyCircularQueue:
def __init__(self, k):
self.CircQueue = [-1]*k
self.k, self.front, self.end = k, 0, 0
def enQueue(self, value):
if self.isFull(): return False
self.end -= 1
self.CircQueue[self.end % self.k] = value
return True
def deQueue(self):
if self.isEmpty(): return False
self.front -= 1
self.CircQueue[self.front % self.k] = -1
return True
def Front(self):
if self.isEmpty(): return -1
return self.CircQueue[(self.front - 1) % self.k]
def Rear(self):
if self.isEmpty(): return -1
return self.CircQueue[self.end % self.k]
def isEmpty(self):
return self.front == self.end
def isFull(self):
return self.front - self.end == self.k
If you like the solution, you can upvote it on leetcode discussion section: Problem 0622