Skip to the solution
MediumDSA14 min read

How does collections.deque work internally?

1.0k views

The problem

Question presented to candidate: "Everyone says use a deque instead of a list for a queue. Why? What does a deque look like in memory in CPython, and what does that layout make cheap and what does it make expensive?"

What a strong answer should cover:

  • Layout: a doubly linked list of fixed-size blocks (64 item slots each in CPython), plus leftblock/leftindex and rightblock/rightindex pointing at the two ends; never one big contiguous array.
  • Cost: append, appendleft, pop, popleft are O(1) and never move other items or call realloc; a new block is allocated only every 64 pushes on a side.
  • Contrast with list: list.pop(0) and insert(0, x) shift every element (O(n)), but a list indexes any position in O(1) while deque[i] walks blocks, so the middle is O(n).
  • Extras that fall out of the layout: maxlen (bounded, evicts from the opposite end), rotate(k), no slicing, and "deque mutated during iteration" detection.
  • Why blocks instead of one node per item: far less pointer overhead and far fewer malloc calls; spare blocks are kept on a small free list.
  • Thread safety: the docs describe appends and pops from either end as thread-safe.

Code / implementation expected: Optional β€” demonstrating O(1) ends vs list.pop(0), maxlen, or sketching the block structure.

  • deque
  • data-structures

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonBlock growth, O(1) ends, rotate, maxlen and mutation detection
PythonA toy model of the deque block layout with 4-slot blocks

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 47 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does the logging module work?

Continue