Back to Data Structures & Algorithms
2026-01-246 min read

Deque (Data Structures & Algorithms)

Learn Deque (Data Structures & Algorithms) step by step with clear examples and exercises.

Why This Matters

Welcome to this full guide on Deques, a versatile data structure that plays a crucial role in solving various problems efficiently using Python. This lesson is designed to help you understand the importance of deques, their practical applications, and how to effectively use them in your coding journey. We'll look closely at the core concept, provide a worked example, discuss common mistakes, offer practice questions, and answer frequently asked questions.

Why Deques Matter

Deques (Double-Ended Queues) are essential for many real-world problems where we need to efficiently add or remove elements from both ends of a data structure. They are particularly useful in areas like network simulation, parsing expressions, and implementing game algorithms. Deques can also help you solve complex programming challenges more effectively during coding competitions.

Prerequisites

To fully understand this lesson, you should be familiar with the following:

  • Python basics, including variables, functions, loops, and conditional statements
  • Lists and their basic operations (append, extend, pop, etc.)
  • Basic understanding of data structures and algorithms

Understanding Deques

Before diving into Python's implementation of deques, let's first understand the concept of a deque. A Deque is a double-ended linear collection of elements that allows insertions and removals at both ends. In contrast, lists only allow insertions and removals at one end (the rear), making them less efficient for operations involving both ends.

Advantages of Deques Over Lists

Deques offer several advantages over lists, especially when dealing with insertions and deletions at both ends:

  1. Faster append and pop operations than lists due to amortized constant time complexity (O(1)).
  2. More memory-efficient than lists because deques only need to resize when necessary, while lists require resizing every time they reach their capacity.
  3. Deques can be useful for problems that involve sliding windows or moving averages, as they allow you to easily add new elements and remove old ones from both ends of the window.

Core Concept

In Python, the collections module provides an implementation of deques. To create a deque in Python, you can use the deque() constructor:

import collections
my_deque = collections.deque([1, 2, 3])
print(my_deque) # Output: deque([1, 2, 3])

Basic Operations

Deques support several useful methods for adding and removing elements:

  • appendleft(x): Insert an element x at the front of the deque.
  • append(x): Insert an element x at the end of the deque.
  • pop(): Remove and return the element from the rear of the deque.
  • popleft(): Remove and return the element from the front of the deque.
  • extend(iterable): Add elements from an iterable to the end of the deque.
  • extendleft(iterable): Add elements from an iterable to the front of the deque.

Example: Using Basic Operations

my_deque = collections.deque([1, 2, 3])
print("Original deque:", my_deque)

Append element

my_deque.append(4)

print("After append(4):", my_deque)

Insert element at the front

my_deque.appendleft(0)

print("After appendleft(0):", my_deque)

Remove and print rear element

print("After pop():", my_deque.pop())

Remove and print front element

print("After popleft():", my_deque.popleft())


Output:

Original deque: deque([1, 2, 3])

After append(4): deque([1, 2, 3, 4])

After appendleft(0): deque([0, 1, 2, 3, 4])

After pop(): 3

After popleft(): 0

Worked Example

Let's consider a problem where we need to implement a deque to solve the Sliding Window Maximum problem: Given an array numbers and a sliding window size k, find the maximum number in each contiguous subarray of size k.

import collections
def maxSlidingWindow(numbers, k):
if not numbers or k <= 0:
return []

deque = collections.deque()
result = []

for i in range(len(numbers)):
while deque and deque[-1] < numbers[i]:
deque.pop()
deque.append(numbers[i])

if i >= k - 1:
result.append(deque[0])
if deque[0] == numbers[i-k+1]:
deque.popleft()

return result

Worked Example

numbers = [1, 3, -1, -3, 5, 3, 6, 7]

k = 3

print(maxSlidingWindow(numbers, k)) # Output: [3, 3, 5, 5, 6, 7]


In this example, we use a deque to keep track of the maximum elements in each sliding window. We maintain the invariant that the maximum element for the current subarray is always at the front of the deque. This allows us to efficiently find the maximum number for each subarray as we iterate through the input array.

Common Mistakes

  1. Misunderstanding the time complexity: Deques offer constant-time append() and pop() operations, but the overall time complexity of an algorithm using deques depends on the specific problem being solved. Be sure to analyze the time complexity of your solution when using deques.
  2. Using lists instead of deques: When dealing with insertions and deletions at both ends, deques can offer significant performance improvements compared to lists. Make sure to use deques when appropriate.
  3. Forgetting to handle edge cases: Always ensure that your code handles all possible input scenarios, including empty or partially filled deques, invalid window sizes, and other edge cases.
  4. Not using the right method for adding or removing elements: Familiarize yourself with the various methods available in Python's collections.deque module and use them appropriately to optimize your code.

Common Mistakes (cont'd)

  1. Ignoring the amortized time complexity: While deques offer constant-time operations, it is essential to understand that the amortized time complexity considers the average cost of multiple operations. In some cases, a sequence of operations may result in higher time complexity due to resizing or rebalancing.
  2. Not considering alternative data structures: Depending on the specific problem and requirements, other data structures like stacks, queues, or heaps might be more suitable for certain tasks. Always evaluate your options and choose the most appropriate data structure for each problem.

Practice Questions

  1. Implement a function that checks if two strings are anagrams of each other using deques.
  2. Given a list of numbers, implement a function that returns the median using a deque.
  3. Solve the problem of finding the first non-repeating character in a string using a deque.
  4. Implement a function to check if a given number is a palindrome using a deque.
  5. Given a list of integers, implement a function that returns the kth smallest element using a deque.
  6. Implement a function to find the shortest common supersequence of two strings using a deque.
  7. Solve the problem of finding the maximum sum subarray of size k using a deque.

FAQ

What is the time complexity of appending and popping from a Python deque?

The amortized time complexity for both append() and pop() operations in Python's collections.deque module is O(1).

How does a deque differ from a stack or a queue?

A deque allows insertions and removals at both ends, while a stack only supports additions and removals at the top (last element), and a queue supports additions at the rear and removals at the front.

Can I use deques for implementing priority queues?

Yes, you can implement a priority queue using Python's heapq module or by sorting the elements in the deque based on their priorities. However, if you need to frequently add and remove elements with the same priority, it might be more efficient to use a heap-based priority queue instead.

How do I handle resizing when using deques?

Python's collections.deque automatically handles resizing as needed when the capacity is exceeded or when elements are removed from the deque. You don't need to worry about resizing manually.

What is the space complexity of a Python deque?

The space complexity of a Python deque is O(n), where n is the number of elements in the deque. This is because each element requires one unit of memory, and there are no additional overheads for managing the deque.

Deque (Data Structures & Algorithms) | Data Structures & Algorithms | XQA Learn