Lesson contents

Double-ended queues

A deque lets you add or remove items at either end. Decide which end to use for each action.

Simple example

Start with 4 and 6 in order. Add 2 at the front and print the new order.

Start4 6
Result2 4 6
lesson.dart
void main() {
    final slots = [0, 4, 6, 0];
    var front = 1;
    final back = 2;
    front -= 1;
    slots[front] = 2;
    var i = front;
    while (i <= back) {
        print(slots[i]);
        i += 1;
    }
}
Output
2
4
6
Advertisements

Everyday examples

Add a replacement shuttle

Shuttles B and C are lined up. Shuttle A returns to cover the next trip. Place it first.

StartB C
ResultA B C

Insert at the front. The regular order of B and C stays the same.

Restock a two-sided display

Books 3 and 5 sit on a display open at both ends. Add book 7 on the right and take one from the left. Which books remain?

Start3 5
Result5 7

Append 7, then remove 3 from the other end.

Cancel the newest pickup

Pickups 6, 9 and 2 are queued. The newest customer cancels before service. What stays in line?

Start6 9 2
Result6 9

Remove 2 from the back. The front customer, 6, keeps their turn.

Cost and limits

A circular array or a doubly linked list can support both ends efficiently. Fast end operations do not automatically make middle insertion fast.