Open In App

Implementation of Deque using Array - Simple

Last Updated : 12 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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-Array
Deque using Array

Basic 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();

Output
5 10 20 30 
10 20 
1 10 20 50 
OperationTime 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.

Next Article
Article Tags :
Practice Tags :

Similar Reads