Deque

DSA · Stacks and Queues

Theory

A deque (double-ended queue) allows adding and removing items at both the front and the back in O(1). It can act as both a stack and a queue. Python's collections.deque also supports a maxlen that automatically drops the oldest items, which is ideal for keeping the last N events.

Why we use it

It combines stack and queue behaviour efficiently and powers the sliding-window maximum technique.

When to use it

Use a deque for sliding window problems, recent-history buffers, palindrome checks and work-stealing schedulers.

How it works

  1. Empty deque
  2. Add? Yes: appendleft (front) or append (rear). No: Remove.
  3. Remove from which end? Yes: popleft (front). No: pop (rear).
  4. All operations O(1)

Syntax

d = deque()
d.append(x); d.appendleft(x)
d.pop();     d.popleft()
deque(maxlen=3)   # keeps only the last 3 items

Example

from collections import deque

recent = deque(maxlen=3)
for page in ["home", "sql", "python", "dsa", "blog"]:
    recent.append(page)
    print("Visited", page, "| last 3:", list(recent))

d = deque([2, 3])
d.appendleft(1)
d.append(4)
print("Both ends:", d.popleft(), d.pop(), "| left:", list(d))

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic