Deque or Double Ended Queue is a type of queue in which insertion and removal of elements can either be performed from the front or the rear. Thus, it does not follow FIFO rule (First In First Out).
Representation of Deque
Below is the circular array implementation of deque. In a circular array, if the array is full, we start from the beginning.
But in a linear array implementation, if the array is full, no more elements can be inserted. In each of the operations below, if the array is full, "overflow message" is thrown.
Before performing the following operations, these steps are followed.
front = -1
and rear = 0
.Initialize an array and pointers for deque
This operation adds an element at the front.
front < 1
, reinitialize front = n-1
(last index).Shift front to the endarray[front]
.Insert the element at FrontThis operation adds an element to the rear.
rear = 0
.array[rear]
.Insert the element at rear
The operation deletes an element from the front.
front = -1
), deletion cannot be performed (underflow condition).front = rear
), set front = -1
and rear = -1
.front = n - 1
), set go to the front front = 0
.front = front + 1
.Increase the frontThis operation deletes an element from the rear.
front = -1
), deletion cannot be performed (underflow condition).front = rear
), set front = -1
and rear = -1
, else follow the steps below.rear = 0
), set go to the front rear = n - 1
.rear = rear - 1
.Decrease the rearThis operation checks if the deque is empty. If front = -1
, the deque is empty.
This operation checks if the deque is full. If front = 0
and rear = n - 1
OR front = rear + 1
, the deque is full.
Python
Java
C
C++
# Deque implementaion in python
class Deque:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def addRear(self, item):
self.items.append(item)
def addFront(self, item):
self.items.insert(0, item)
def removeFront(self):
return self.items.pop(0)
def removeRear(self):
return self.items.pop()
def size(self):
return len(self.items)
d = Deque()
print(d.isEmpty())
d.addRear(8)
d.addRear(5)
d.addFront(7)
d.addFront(10)
print(d.size())
print(d.isEmpty())
d.addRear(11)
print(d.removeRear())
print(d.removeFront())
d.addFront(55)
d.addRear(45)
print(d.items)
The time complexity of all the above operations is constant i.e. O(1)
.