Python Snippet

deque for O(1) Append and Pop on Both Ends

Difficulty: Easy

A `collections.deque` (double-ended queue) supports O(1) `append`, `appendleft`, `pop`, and `popleft`, while a Python `list` is O(n) for left-side operations. This snippet covers the deque-as-queue pattern that powers BFS, the deque-as-rolling-buffer pattern with `maxlen`, and the rotate trick for cyclic processing.

Code Snippets
/

deque for O(1) Append and Pop on Both Ends

deque for O(1) Append and Pop on Both Ends

A `collections.deque` (double-ended queue) supports O(1) `append`, `appendleft`, `pop`, and `popleft`, while a Python `list` is O(n) for left-side operations. This snippet covers the deque-as-queue pattern that powers BFS, the deque-as-rolling-buffer pattern with `maxlen`, and the rotate trick for cyclic processing.

Python
Easy
3 snippets
py-collections
py-standard-library
code-template
queue

920 views

9

BFS needs a FIFO queue: append to the end, popleft from the front. A Python list supports append in O(1) but pop(0) in O(n) because every other element must shift. deque makes both O(1), which is what makes a BFS on a million-node graph feasible. Always reach for deque when the algorithm needs a real queue; using a list 'because it works' is one of the most common Python performance bugs in graph code.