Queue and deque
Breadth-first search, scheduling, and sliding-window maximum (with a deque).
High interview relevanceRoadmap: Beginner
| Time | Enqueue and dequeue O(1) with a deque |
|---|---|
| Space | O(n) |
Why it costs this much
A deque supports adding and removing at both ends without moving the other items.
Code
from collections import deque
q = deque()
q.append(x) # enqueue: O(1)
q.popleft() # dequeue: O(1)
# lst.pop(0) # O(n): shifts everything leftPython is the baseline example used across the site.
Common pitfalls
list.pop(0) shifts every element, so it costs O(n) per dequeue. Indexing into the middle of a Python deque is also O(n).
Operation by operation
| Operation | Best | Average | Worst | Space |
|---|---|---|---|---|
| Queue enqueue and dequeue | O(1) | O(1) | O(1) with a deque; O(n) per dequeue with a shifting array | O(1) |
Queue enqueue and dequeue. Backed by a deque, circular buffer, or linked list. Python list.pop(0) and JavaScript Array.shift can be O(n). Use collections.deque in Python.