Bitpath

Lesson 1 · Unit 02

First in, first out

Why the front of an array is expensive, and what to do instead

12 exercisesabout 3 min

What you practise

  • Why removing from the front of an array is O(n)
  • A deque or a head index instead

Try a question from this lesson

Pick one

Three print jobs arrive: A, then B, then C. The printer always takes the job that has waited longest. In what order do they print?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Join at the back, leave from the front

A queue has two moves. Enqueue adds an item at the back. Dequeue removes the item at the front and hands it to you.

Items leave in exactly the order they arrived.

from collections import deque

queue = deque()
queue.append("A")        # enqueue
queue.append("B")        # enqueue
first = queue.popleft()  # dequeue: "A"
print(first, len(queue))
const queue = [];
queue.push("A");              // enqueue
queue.push("B");              // enqueue
const first = queue.shift();  // dequeue
console.log(first, queue.length);
const queue: string[] = [];
queue.push("A");              // enqueue
queue.push("B");              // enqueue
const first = queue.shift();  // dequeue
console.log(first, queue.length);

Python notedeque (say "deck") is Python's queue type. Its popleft() is O(1); list.pop(0) is not.

JavaScript noteshift() is correct but O(n) on a long array: every remaining item moves down one index. This lesson shows the fix.

TypeScript noteshift() returns string | undefined, because the array might be empty.

Concept

Move a marker, not the items

Shifting is the whole cost, so do not shift. Leave the items where they are and keep an index, head, that marks the front.

Dequeue reads the item at head and adds 1 to head. Nothing moves: O(1).

items = ["A", "B", "C"]
head = 0

first = items[head]   # dequeue: "A"
head += 1             # nothing shifts
print(first, items[head])
const items = ["A", "B", "C"];
let head = 0;

const first = items[head]; // dequeue
head += 1;                 // no shifting
console.log(first, items[head]);
const items = ["A", "B", "C"];
let head = 0;

const first = items[head]; // dequeue
head += 1;                 // no shifting
console.log(first, items[head]);

Python noteIn Python you rarely write this by hand: collections.deque gives you an O(1) popleft().

JavaScript noteJavaScript has no built-in queue type, so the head index is the standard way to get an O(1) dequeue.

TypeScript notelet head = 0 needs no annotation: TypeScript infers number. Use let, not const, because it changes.

9 more exercises in the app

  • 3× type the answer
  • 2× multiple choice
  • 1× fill the blanks
  • 1× match the pairs
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy