Skip to content

Queues

Import packages

from collections import deque

deque is a double-ended queue that allows you to efficiently add and remove elements from both ends.

queue = deque()
queue
deque([])

Add an element to the right side - O(1)

1
2
3
4
queue.append(1)
queue.append(2)

queue
deque([1, 2])

Dequeue an element from the left side - O(1)

If simply using pop() it will act as a stack, removing the last element added (LIFO).

queue.popleft()
1

Peek at the leftmost element without removing it - O(1)

queue[-1]
2