Skip to main content
Data Structures
CHAPTER 14 Beginner

Deque (Double Ended Queue)

Updated: May 17, 2026
15 min read

# CHAPTER 14

Deque (Double Ended Queue)

1. Introduction

So far, we have looked at structures with extremely strict rules. A Stack only allows you to touch the Top (LIFO). A Queue only allows you to add to the Rear and remove from the Front (FIFO). But what if you need a flexible hybrid? Imagine a VIP line at an airport. Normally, people enter the back of the line. But a VIP customer might be allowed to skip the entire line and enqueue directly at the absolute front! Or perhaps a customer at the very back of the line decides to leave early, requiring a dequeue from the rear. This ultimate flexibility is achieved using a Deque (pronounced "deck"), short for Double Ended Queue.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Define the structural freedoms of a Deque.
  • Execute the four distinct Deque operations.
  • Understand how Doubly Linked Lists power the ideal Deque implementation.
  • Identify scenarios where a Deque outperforms standard Stacks or Queues.

3. The Four Core Operations

A Deque shatters the strict rules of LIFO and FIFO. You are granted mathematical access to manipulate *both* ends of the structure simultaneously.
  1. 1. insertFront(data): Injects data directly to the Head.
  1. 2. insertRear(data): Appends data to the Tail. (Standard Queue behavior).
  1. 3. deleteFront(): Removes data from the Head. (Standard Queue behavior).
  1. 4. deleteRear(): Removes data from the Tail.

4. Implementation Strategy

How do we build a structure that allows O(1) instantaneous manipulation at both ends?
  • Using an Array: We can use the math from Chapter 13 (Circular Queue) and expand it to allow pointers to move backward front = (front - 1 + MAX) % MAX.
  • Using a Doubly Linked List (The Best Way!): Because a Doubly Linked List has prev and next pointers, and explicitly tracks the head and tail, we can effortlessly snap new nodes onto either end in O(1) time.
java
1234567891011121314151617181920212223242526
// Java Example: Deque using java.util.LinkedList (which IS a Doubly Linked List!)
import java.util.Deque;
import java.util.LinkedList;

public class DequeExample {
    public static void main(String[] args) {
        // We instantiate a Deque interface using the LinkedList class
        Deque<String> vipLine = new LinkedList<>();

        // Normal people join the back of the line
        vipLine.addLast("Bob");   // insertRear
        vipLine.addLast("Charlie");

        // VIP skips the line and goes straight to the front!
        vipLine.addFirst("Alice_VIP"); // insertFront

        System.out.println(vipLine); 
        // Output: [Alice_VIP, Bob, Charlie]

        // The person at the very back leaves the line early
        vipLine.removeLast(); // deleteRear
        
        System.out.println(vipLine); 
        // Output: [Alice_VIP, Bob]
    }
}

5. Variations of the Deque

Depending on system requirements, architects sometimes lock down specific capabilities of the Deque:
  • Input-Restricted Deque: Insertions are restricted strictly to ONE end (Rear), but Deletions can occur at BOTH ends.
  • Output-Restricted Deque: Deletions are restricted strictly to ONE end (Front), but Insertions can occur at BOTH ends.

6. Complexity Analysis

Because the Deque only interacts with the absolute boundaries of the dataset (the ends) and never traverses the middle, the performance is theoretically flawless.
OperationTime Complexity
Insert FrontO(1)
Insert RearO(1)
Delete FrontO(1)
Delete RearO(1)

7. Real-World Applications

  1. 1. Python's Default Queue: In Python, the collections.deque module is the undisputed standard for building both Stacks AND Queues, because it is hyper-optimized in C to allow O(1) appends and pops from both sides.
  1. 2. Web Browser History: Navigating back and forward through recently visited URLs.
  1. 3. A Palindrome Checker Algorithm: A Deque can instantly check if "RADAR" is a palindrome by simultaneously deleteFront() (R) and deleteRear() (R) and checking if they match, moving inward!
  1. 4. Stealing CPU Tasks: In multi-core processing (like the Go programming language scheduler), if Core #1 finishes its task queue early, it can execute a deleteRear() on Core #2's queue, "stealing" a task from the back of the line to process it!

8. Mini Project: Palindrome Checker using Deque

Let's see how elegantly a Deque solves string logic.
python
1234567891011121314151617
# Python Example: Palindrome check via Deque
from collections import deque

def check_palindrome(word):
    char_deque = deque(word) # Instantly creates a Deque of letters
    
    while len(char_deque) > 1:
        # Pull from both ends simultaneously!
        front_char = char_deque.popleft()
        rear_char = char_deque.pop()
        
        if front_char != rear_char:
            return False # Mismatch found!
            
    return True # Clean sweep

print(check_palindrome("racecar")) # True

9. Common Mistakes

  • Using Deques when a Stack is sufficient: A Deque is larger and more complex. If you only need LIFO behavior, mathematically restrict yourself by using a standard Stack. Don't give future developers the ability to insertFront if the business logic explicitly forbids it!

10. Best Practices

  • Master Python's Deque: If you ever take a FAANG technical interview in Python, NEVER use list.pop(0). The interviewer will fail you for executing an O(n) shift. You must explicitly import and use collections.deque.popleft() to demonstrate you understand O(1) architecture.

11. Exercises

  1. 1. Trace the contents of an empty Deque after: insertFront(1), insertRear(2), insertFront(3), deleteRear(). What is left in the Deque?
  1. 2. Explain how you could use a Deque to perfectly simulate the behavior of a standard Stack. Which two operations would you restrict?

12. MCQs with Answers

Question 1

What is the fundamental architectural advantage of a Deque (Double Ended Queue) over a standard Queue?

Question 2

When implementing an optimized Deque, what underlying data structure is most commonly utilized to guarantee mathematically pure O(1) performance for all four boundary operations?

Question 3

If an engineer restricts a Deque to ONLY allow insertFront and deleteFront, what Abstract Data Type have they perfectly simulated?

Question 4

Python developers almost universally utilize the collections.deque module instead of a standard list to build Queues. What exact Time Complexity disaster does this prevent?

Question 5

In advanced OS Kernel design, "Work Stealing" algorithms allow idle CPU Core A to steal tasks from overloaded CPU Core B. Which Deque operation allows Core A to steal a task without interrupting Core B's standard FIFO execution?

Question 6

What is an "Input-Restricted" Deque?

Question 7

When utilizing a Deque to execute a highly optimized Palindrome verification algorithm (e.g., checking the word "RACECAR"), what is the exact operational sequence?

Question 8

What is the guaranteed execution Time Complexity of the insertFront() operation on a Doubly Linked Deque?

Question 9

If a Deque begins completely empty, trace the exact internal state after the following sequence: insertRear(10), insertFront(20), insertRear(30). What is the physical order from Front to Rear?

Question 10

Why is standardizing on Deques sometimes considered a bad architectural practice if a simple Stack is all that is required by the business logic?

13. Interview Preparation

Top Interview Questions:
  • *Algorithmic Coding:* "Given an array and an integer K, find the maximum element for each and every contiguous subarray of size K. Solve this in purely O(n) time." *(Answer: The famous Sliding Window Maximum problem! It is solved optimally by utilizing a Deque to store the indexes of mathematically useful elements as the window slides right).*

Common Pitfalls:

  • In whiteboard coding, attempting to implement a Deque using a Linear Array without applying the Modulo Arithmetic wrap-around logic from Chapter 13. A Linear Array Deque will instantly suffer from False Overflows on both ends!

14. FAQs

Q: Does JavaScript have a built-in Deque? A: Surprisingly, no! JS arrays use push(), pop(), shift(), and unshift(), but shift() and unshift() (Front operations) take O(n) time because JS Arrays are contiguous blocks. If you need a fast Deque in JS, you must build one manually or import an NPM package!

15. Summary

The Deque is the ultimate flexible boundary data structure. By breaking the strict isolation of LIFO and FIFO, it grants software engineers O(1) manipulation of both ends of a sequence, enabling advanced algorithms like Sliding Windows and Palindrome checks.

16. Next Chapter Recommendation

What if fairness in a line shouldn't be based on *when* you arrived, but on *how important* you are? If a patient with a papercut and a patient with a heart attack arrive at the ER, FIFO logic is literally deadly. In Chapter 15: Priority Queue, we will program data to automatically sort itself by urgency.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·