High interview relevanceRoadmap: Beginner
TimeEnqueue and dequeue O(1) with a deque
SpaceO(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 left

Python 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

OperationBestAverageWorstSpace
Queue enqueue and dequeueO(1)O(1)O(1) with a deque; O(n) per dequeue with a shifting arrayO(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.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list