← Data & decisions STAGE 02 · 26 MIN

Choose your data structure

Match lists, maps, sets, and queues to the operations your system actually performs.

Open in the laboratory ↗

BY THE END, YOU CAN

  • Choose a collection from required operations
  • Distinguish order, identity, and uniqueness
  • Use a deque for a FIFO workload
Start from the operations you need, then pick the structure that makes them cheap.

Diagram description: Add at the back, take from the front → deque; Find a job by ID → dict; Always the most urgent next → heapq

Start from operations

A data structure is a set of tradeoffs.

A list is useful for ordered traversal and indexed access. A dictionary associates keys with values. A set represents membership without duplicates.

The right question is not which structure is fastest in general, but which operations your workload needs. Relay needs to receive jobs at one end and remove them at the other, while a status lookup needs to find a job by identifier. These are different needs and can justify different structures.

Queues have a direction

FIFO means first in, first out.

Removing index zero from a Python list shifts the remaining elements, so repeated front removals become expensive as the queue grows. A deque supports efficient addition and removal at both ends and expresses this intent directly. A stack instead removes the most recently added item.

Neither policy is universally better: FIFO fits ordinary arrival order, while a stack is useful for depth-first exploration and undo histories. Name the policy so users know what order to expect.

Python
from collections import deque

pending = deque(["email", "report"])
pending.append("thumbnail")
next_job = pending.popleft()
print(next_job)

One fact, multiple views

A dictionary keyed by job ID can provide fast expected lookup, while a queue holds IDs in processing order.

This duplicates references to identity, not necessarily the whole job. Maintaining multiple views creates an invariant: every queued ID must refer to an existing job. Decide what happens when cancellation removes a job from one view but not another.

An index saves work during reads but costs work during writes. That same idea reappears in databases, search engines, and caches at much larger scale.

COMMON FAILURE MODE

Keeping a queue and a status dictionary without defining how they stay consistent can produce missing or duplicate work.

TRY IT YOURSELF

Choose structures for pending job order, status by ID, and a collection of already-seen IDs. Explain the dominant operation for each choice.

RETRIEVAL CHECK / APPLY THE IDEA

Make the call in the laboratory.

The two-question checkpoint, your notes, and your saved progress are in the laboratory. Free, with no account.

Open in the laboratory ↗

CONNECT IT TO RELAY

Replace Relay's front-popped list with a deque and add a dictionary for status lookup. Document the consistency rule between them.