Implementation of Deque using Array - Simple
Last Updated :
12 Mar, 2025
A Deque (Double-Ended Queue) is a data structure that allows insertion and deletion of elements at both ends (front and rear). This flexibility makes it more versatile than a regular queue, where insertion and deletion can only happen at one end. In this article, we will explore how to implement a deque using a simple array.
Key Features of a Deque
- Insertions and deletions from both ends: You can add or remove elements from both ends of the deque.
- Fixed size: The size of the deque is fixed when the array is created.
- Efficient operations: Insertion and deletion from both ends are efficient if there is space available in the array.
Deque using ArrayBasic Operations of a Deque Using a Simple Array
The key operations that can be performed on a deque implemented using a simple array:
1. Initialization
The deque is initialized using an array and two pointers, front
and rear
, which track the positions of the front and rear elements.
front
and rear
are initialized to -1
to indicate that the deque is empty.- The array
arr
will store the elements of the deque.
2. Insert at Front
To insert an element at the front of the deque, we shift all the elements one position to the right and place the new element at the front.
- If the deque is empty, both the
front
and rear
pointers are initialized to 0. - If the
front
pointer is at 0, there is no space for insertion at the front, and an error is returned. - If there is space, all elements are shifted to the right, creating room for the new element at the front.
3. Insert at Rear
To insert an element at the rear of the deque, we place it at the position of the rear pointer and increment the rear.
- If the deque is empty, both
front
and rear
are set to 0
. - If there’s space, the element is inserted at the rear pointer and the rear is incremented.
4. Delete from Front
To delete an element from the front of the deque, we simply increment the front
pointer to remove the element. If there’s only one element, both the front
and rear
are reset to -1
.
- If there is only one element, reset both
front
and rear
to -1
. - Otherwise, increment the
front
pointer to remove the element.
5. Delete from Rear
To delete an element from the rear of the deque, we decrement the rear
pointer. If there’s only one element, reset both front
and rear
.
- If there’s only one element, reset both
front
and rear
. - Otherwise, decrement the
rear
pointer to remove the element.
6. Get Front and Rear
- These functions return the elements at the front or rear of the deque.
7. Check if Empty or Full
isEmpty
checks if the front
pointer is -1
, indicating that the deque is empty.isFull
checks if the rear
pointer has reached the last index of the array.
C++
#include <iostream>
#include <vector>
using namespace std;
class Deque {
vector<int> dq;
public:
bool isEmpty() { return dq.empty(); }
void insertFront(int x) {
dq.insert(dq.begin(), x);
}
void insertRear(int x) {
dq.push_back(x);
}
void deleteFront() {
if (!isEmpty()) dq.erase(dq.begin());
}
void deleteRear() {
if (!isEmpty()) dq.pop_back();
}
int getFront() {
return isEmpty() ? -1 : dq.front();
}
int getRear() {
return isEmpty() ? -1 : dq.back();
}
void display() {
for (int x : dq) cout << x << " ";
cout << "\n";
}
};
int main() {
Deque dq;
dq.insertRear(10);
dq.insertRear(20);
dq.insertFront(5);
dq.insertRear(30);
dq.display();
dq.deleteFront();
dq.deleteRear();
dq.display();
dq.insertFront(1);
dq.insertRear(50);
dq.display();
}
C
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct Deque {
int items[MAX];
int front;
int rear;
} Deque;
void initDeque(Deque* dq) {
dq->front = -1;
dq->rear = -1;
}
int isEmpty(Deque* dq) {
return dq->front == -1;
}
int isFull(Deque* dq) {
return (dq->rear + 1) % MAX == dq->front;
}
void insertFront(Deque* dq, int x) {
if (isFull(dq)) return;
if (isEmpty(dq)) {
dq->front = 0;
dq->rear = 0;
} else {
dq->front = (dq->front - 1 + MAX) % MAX;
}
dq->items[dq->front] = x;
}
void insertRear(Deque* dq, int x) {
if (isFull(dq)) return;
if (isEmpty(dq)) {
dq->front = 0;
dq->rear = 0;
} else {
dq->rear = (dq->rear + 1) % MAX;
}
dq->items[dq->rear] = x;
}
void deleteFront(Deque* dq) {
if (isEmpty(dq)) return;
if (dq->front == dq->rear) {
dq->front = -1;
dq->rear = -1;
} else {
dq->front = (dq->front + 1) % MAX;
}
}
void deleteRear(Deque* dq) {
if (isEmpty(dq)) return;
if (dq->front == dq->rear) {
dq->front = -1;
dq->rear = -1;
} else {
dq->rear = (dq->rear - 1 + MAX) % MAX;
}
}
int getFront(Deque* dq) {
return isEmpty(dq) ? -1 : dq->items[dq->front];
}
int getRear(Deque* dq) {
return isEmpty(dq) ? -1 : dq->items[dq->rear];
}
void display(Deque* dq) {
if (isEmpty(dq)) return;
int i = dq->front;
while (1) {
printf("%d ", dq->items[i]);
if (i == dq->rear) break;
i = (i + 1) % MAX;
}
printf("\n");
}
int main() {
Deque dq;
initDeque(&dq);
insertRear(&dq, 10);
insertRear(&dq, 20);
insertFront(&dq, 5);
insertRear(&dq, 30);
display(&dq);
deleteFront(&dq);
deleteRear(&dq);
display(&dq);
insertFront(&dq, 1);
insertRear(&dq, 50);
display(&dq);
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class Deque {
List<Integer> dq = new ArrayList<>();
public boolean isEmpty() { return dq.isEmpty(); }
public void insertFront(int x) {
dq.add(0, x);
}
public void insertRear(int x) {
dq.add(x);
}
public void deleteFront() {
if (!isEmpty()) dq.remove(0);
}
public void deleteRear() {
if (!isEmpty()) dq.remove(dq.size() - 1);
}
public int getFront() {
return isEmpty() ? -1 : dq.get(0);
}
public int getRear() {
return isEmpty() ? -1 : dq.get(dq.size() - 1);
}
public void display() {
for (int x : dq) System.out.print(x + " ");
System.out.println();
}
}
public class Main {
public static void main(String[] args) {
Deque dq = new Deque();
dq.insertRear(10);
dq.insertRear(20);
dq.insertFront(5);
dq.insertRear(30);
dq.display();
dq.deleteFront();
dq.deleteRear();
dq.display();
dq.insertFront(1);
dq.insertRear(50);
dq.display();
}
}
Python
class Deque:
def __init__(self):
self.dq = []
def is_empty(self):
return len(self.dq) == 0
def insert_front(self, x):
self.dq.insert(0, x)
def insert_rear(self, x):
self.dq.append(x)
def delete_front(self):
if not self.is_empty():
self.dq.pop(0)
def delete_rear(self):
if not self.is_empty():
self.dq.pop()
def get_front(self):
return -1 if self.is_empty() else self.dq[0]
def get_rear(self):
return -1 if self.is_empty() else self.dq[-1]
def display(self):
print(' '.join(map(str, self.dq)))
if __name__ == '__main__':
dq = Deque()
dq.insert_rear(10)
dq.insert_rear(20)
dq.insert_front(5)
dq.insert_rear(30)
dq.display()
dq.delete_front()
dq.delete_rear()
dq.display()
dq.insert_front(1)
dq.insert_rear(50)
dq.display()
C#
// C# implementation of Deque
using System;
using System.Collections.Generic;
class Deque {
List<int> dq = new List<int>();
public bool IsEmpty() { return dq.Count == 0; }
public void InsertFront(int x) {
dq.Insert(0, x);
}
public void InsertRear(int x) {
dq.Add(x);
}
public void DeleteFront() {
if (!IsEmpty()) dq.RemoveAt(0);
}
public void DeleteRear() {
if (!IsEmpty()) dq.RemoveAt(dq.Count - 1);
}
public int GetFront() {
return IsEmpty() ? -1 : dq[0];
}
public int GetRear() {
return IsEmpty() ? -1 : dq[dq.Count - 1];
}
public void Display() {
foreach (int x in dq) Console.Write(x + " ");
Console.WriteLine();
}
}
class MainClass {
public static void Main(string[] args) {
Deque dq = new Deque();
dq.InsertRear(10);
dq.InsertRear(20);
dq.InsertFront(5);
dq.InsertRear(30);
dq.Display();
dq.DeleteFront();
dq.DeleteRear();
dq.Display();
dq.InsertFront(1);
dq.InsertRear(50);
dq.Display();
}
}
JavaScript
// Deque class implementation in JavaScript
class Deque {
constructor() {
this.dq = [];
}
isEmpty() {
return this.dq.length === 0;
}
insertFront(x) {
this.dq.unshift(x);
}
insertRear(x) {
this.dq.push(x);
}
deleteFront() {
if (!this.isEmpty()) {
this.dq.shift();
}
}
deleteRear() {
if (!this.isEmpty()) {
this.dq.pop();
}
}
getFront() {
return this.isEmpty() ? -1 : this.dq[0];
}
getRear() {
return this.isEmpty() ? -1 : this.dq[this.dq.length - 1];
}
display() {
console.log(this.dq.join(' '));
}
}
const dq = new Deque();
dq.insertRear(10);
dq.insertRear(20);
dq.insertFront(5);
dq.insertRear(30);
dq.display();
dq.deleteFront();
dq.deleteRear();
dq.display();
dq.insertFront(1);
dq.insertRear(50);
dq.display();
Output5 10 20 30
10 20
1 10 20 50
Operation | Time Complexity |
---|
insertFront(x) | O(n) |
insertRear(x) | O(1) |
deleteFront() | O(n) |
deleteRear() | O(1) |
getFront() | O(1) |
getRear() | O(1) |
isEmpty() | O(1) |
isFull() | O(1) |
Advantages and Limitations of Using a Simple Array for Deque
Advantages
- Simple implementation: The array-based implementation is easy to understand and straightforward to code.
Limitations
- Fixed size: The size of the array is fixed at the time of creation. Once the deque is full, no more elements can be inserted unless we resize the array manually.
- Shifting elements: Inserting elements at the front requires shifting all other elements, which can be inefficient for large deques.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem