Profile

Unblock all features

Sign in to track progress and visualise your code.

ntree.ai
Helper data structures and core patterns

Queue

A queue is a collection that gives back the oldest element first: first in, first out (FIFO). You should use a queue whenever elements have to be handled in the order they arrive.

1
2
3
enqueue adds to the back, dequeue takes the front

Time and space complexity

operationtime
add an element to the backO(1)O(1) amortised
remove the front elementO(1)O(1) amortised
read the front elementO(1)O(1)

Implementation

A normal array cannot provide these operations with the same time complexity, because removing its first element shifts every other element. Here is one of the possible implementations with constant time complexity.

Head index

The queue keeps its elements in a dynamic array and the index of its front element, called head.

Enqueue appends the value to the end of the array.

Dequeue returns the element at index head and moves head forward by one instead of removing the element, so nothing shifts.

Compacting

The slots before head are never used again, but they still take memory.

So when head passes half of the array, it is worth migrating all the elements from head into a new array, reset head to zero and drop the old array.

This takes O(n)O(n) time, but it happens only after about n / 2 dequeues. That is why we say dequeue is O(1)O(1) amortised.

012345
head
head = 0

Build it

Implement enqueue, dequeue and peek in the class below. Call compact from dequeue when head passes half of the array.

Build a queue
Python
class Queue:
def __init__(self) -> None:
self.elements = []
self.head = 0
def enqueue(self, value: int) -> None:
# Add value to the back of the queue
pass
def dequeue(self) -> int:
# Remove the front value and return it
return None
def peek(self) -> int:
# Return the front value without removing it
return None
def _compact(self) -> None:
self.elements = self.elements[self.head:]
self.head = 0
queue = Queue()
for value in [1, 2, 3]:
queue.enqueue(value)
print(queue.dequeue(), queue.dequeue())
for value in [4, 5]:
queue.enqueue(value)
print(queue.peek())
print(queue.dequeue(), queue.dequeue(), queue.dequeue())
Was this lesson helpful?