Bitpath

Lesson 2 · Unit 02

Both ends

Deques, a recent-events counter and the circular buffer

13 exercisesabout 3 min

What you practise

  • Deque operations
  • A recent-events counter
  • The circular buffer idea

Try a question from this lesson

Pick one

A browser remembers only your 3 most recent pages. You open a 4th. Which page should it forget?

The ideas

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

Concept

A deque works at both ends

A deque (say "deck") has four moves: add at the back, remove from the back, add at the front, remove from the front.

A real deque does all four in O(1). It can play a stack or a queue, or both at once.

from collections import deque

d = deque([2, 3])
d.appendleft(1)   # 1 2 3
d.append(4)       # 1 2 3 4
d.popleft()       # 2 3 4
d.pop()           # 2 3
print(*d)
const d = [2, 3];
d.unshift(1);   // 1 2 3
d.push(4);      // 1 2 3 4
d.shift();      // 2 3 4
d.pop();        // 2 3
console.log(d.join(" "));
const d = [2, 3];
d.unshift(1);   // 1 2 3
d.push(4);      // 1 2 3 4
d.shift();      // 2 3 4
d.pop();        // 2 3
console.log(d.join(" "));

Python notedeque(maxlen=3) goes one step further: it drops the oldest item by itself when a fourth arrives.

JavaScript noteArrays have all four methods, but unshift and shift are O(n). For heavy use of the front, use a head index or a circular buffer.

TypeScript noteTypeScript infers number[] for d from [2, 3], so d.push("x") would be a compile error.

Concept

A window of recent events

"How many requests arrived in the last 10 seconds?" is a deque question.

Each new timestamp joins at the back. Timestamps older than 10 seconds are at the front, because they arrived first, so they leave from the front. What remains is exactly the recent ones.

Concept

A circular buffer: an array bent into a ring

A circular buffer is a fixed-size array used as a ring. head is the index of the front item, and size counts the items.

The next free slot is (head + size) % capacity: past the last index, it wraps around to 0. Removing from the front just moves head forward, wrapping the same way.

capacity = 4
head, size = 3, 2    # items in slots 3, 0
back = (head + size) % capacity
print(back)          # 1: next free slot
const capacity = 4;
const head = 3;
const size = 2;     // items in slots 3, 0
const back = (head + size) % capacity;
console.log(back);  // 1: next free slot
const capacity = 4;
const head = 3;
const size = 2;     // items in slots 3, 0
const back = (head + size) % capacity;
console.log(back);  // 1: next free slot

9 more exercises in the app

  • 1× match the pairs
  • 3× type the answer
  • 1× fill the blanks
  • 2× multiple choice
  • 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