Skip to the workspace
Pebellslearn by building
Linked Lists, Stacks & Queues  ›  Lesson

Queues, Deques & Up-Next

Queues 22 minFirst in, first out, with O(1) work at both ends

dsa / Queues, Deques & Up-Next

Explore each scene at your own pace.

01 · Queue up tracks for Tunebox's up-next list

Queue up tracks for Tunebox's up-next list

Queues, Deques & Up-Next

Definition
A queue is a collection where items are added at the back and removed from the front, so the item that has waited longest is served first (first in, first out); a deque makes both ends cheap to change.
In plain words
It is a line at a shop counter: new people join at the back, and the person at the front is served next. Nobody gets to jump in the middle, and a deque is a line where you can also add or leave at the front.

In short: a queue serves whatever has waited longest. Enqueue adds at the back, dequeue removes from the front — FIFO, first in, first out, the opposite of a stack. A plain Python list can do this with append + pop(0), but pop(0) shifts every remaining item left: O(n), getting slower the longer the queue. collections.deque stores items in a chain of small blocks so both ends are O(1) — the fix this lesson builds around.

A line of people at a counter: a new person joins the back in one step, the person at the front is served in one step, and a crossed-out hand reaching into the middle of the line is marked 'never — O(n)'

Queue up tracks for Tunebox's up-next list

python

The answer is right, but the mistake is not noticing what pop(0) costs to get there — every remaining item shifts one slot left:

What does this print?
queue = ["A", "B", "C"]
first = queue.pop(0)
print(queue.index("C"))

With 100,000 tracks waiting, one dequeue moves 99,999 items; serving the whole queue that way moves about n²/2 items. deque ("deck") fixes it — neither end ever shifts anything:

python

❓ Cross-question — "So why not use a deque for everything?" Fast ends cost a slow middle. q[i] is O(n) near the middle of a deque, where a list is O(1), and a deque can't be sliced. Index into it → list; work at the ends → deque.

Scene 1 of 7
Project context and further resources
You're building a piece ofTunebox — the player
This piece — up_next(): The first-in, first-out queue of tracks waiting to play.
Scenario You queue Chorus behind Intro and Verse, then tap "play next" on a friend's track. Tunebox's up-next queue serves tracks in arrival order, but lets "play next" jump to the front.
up_next.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
up_next(queue, ops) → listThe up-next queue after every op, front first.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.