Queues

First in, first out · Part of Lists, stacks and hash

Key idea

Practice

6 questions · about 3 min

Explained step by step

Queue

A queue follows the rule "first in, first out". It's like the line at a bank: newcomers go to the back and the one at the front is served. The 2 ends are called the front and the rear. Adding at the rear is called enqueue and removing the front one is called dequeue. Both operations are O(1).

To trace a queue by hand, you write down its contents with the front on the left. Enqueue adds on the right; dequeue removes the leftmost. For example: enqueue A, enqueue B, dequeue (A comes out), enqueue C, dequeue (B comes out), dequeue (C comes out). They come out A, B, C: the same order they went in. With a stack, the same steps would give B, C, A.

A queue can be built with a linked list: the head is the front and the list's last node is the rear. Enqueue hooks a new node after the last one; dequeue removes the head. Both are O(1) if you keep a reference to the first and another to the last. Without the reference to the last, enqueueing would mean walking the whole list to find it.

With an array, removing the first element by shifting everyone would be O(n). The trick is to shift nothing: you keep the front's index and the number of elements. The rear is at front + count. Enqueue writes at the rear and adds 1 to the count; dequeue just moves the front 1 spot and subtracts 1. Both operations are O(1).

Queues are useful whenever something is served in order of arrival. An online store's orders go into a queue and are processed in order, even if thousands arrive per second during a sale. Documents you send to print wait in a queue. So do a kitchen's orders. The difference from a stack is fairness: in the queue, whoever waits longest goes first.

Circular array

In the array-based queue, the front and rear move to the right and at some point reach the end of the array, even if there's free room at the start. The fix is to treat the array as a circle: when an index passes the last one, it goes back to 0. It's computed with the remainder of a division: with length 5, the index after 4 is (4 + 1) % 5 = 0. That way the queue uses the whole array without shifting anything.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

First in, first out