Stacks and queues: operations, uses and costs

Video lessonComing soon

1 A pile of plates and a ticket line

The undo button in an editor undoes the newest change first. A printer works the other way round: the page sent first comes out first. Neither one needs the middle of its list, only an end.

A pile of plates works like undo. We put a plate on top and take a plate from the top, so the last one in is the first one out. This is a stack.

A ticket line works like the printer. People join at the rear and leave from the front, so the first one in is the first one out. This is a queue.

385top →
A stack: 5 went in last, so it leaves first
308152frontrear
A queue: 3 went in first, so it leaves first

Each one has only a few operations:

StackQueue
Addpush onto the topenqueue at the rear
Removepop from the topdequeue from the front
Lookpeek at the toplook at the front
Checkempty, sizeempty, size

There is no "read the middle". That limit is the point: an end is cheap to reach, so every operation can be O(1).

The standard library lesson used the ready-made types. This lesson builds them, as the problems in this subtopic ask. Along the way, it shows which library calls only look O(1).

2 A stack on an array

A stack fits an array with no tricks. The bottom plate sits at index 0, and one number, size, counts the values. The top is at index size - 1, and the next push goes to index size. Here the array has room for four values. We push 3, 8 and 5, pop once, then push 1:

A stack on an array of 4
308123top
Push 3, then 8. size = 2

Step 3 is the one to notice. A pop erases nothing. The 5 is still in memory, but size leaves it out of the stack, and the next push writes over it.

push(x):  if size == capacity: full
          data[size] = x
          size = size + 1

pop():    if size == 0: empty
          size = size - 1
          return data[size]

peek():   if size == 0: empty
          return data[size - 1]

All the work happens at the end of the array, so nothing shifts, and each operation is O(1).

Pushing onto a full array is an overflow, and popping an empty stack is an underflow. A fixed array must refuse both. A dynamic array, such as vector, is never full. It grows itself, and a push stays O(1) on average, as the arrays lesson showed.

3 A queue on an array: move the front, not the values

In a ticket line, everyone steps forward when the front person leaves. On an array, stepping forward is a shift: every value moves one place left.

3081523
Dequeue 3 by shifting: 8 and 5 move
3081523front
Dequeue 3 by moving front: nothing moves

Each shift costs about n steps. A queue that takes in 10⁵ values and hands them all back does around 10¹⁰ steps. At about 10⁸ steps a second, that is far past the time limit, so it gets TLE.

The fix is to move the ticket counter instead of the people. We keep an index, front. A dequeue reads data[front] and adds 1 to front, which is O(1). The old value stays in memory, outside the queue, as with the stack's pop.

This raises a new problem. The front walks right, and so does the rear. Soon the rear reaches the end of the array, while the slots before front sit empty:

30815213frontrear
Slots 0 and 1 are free, but there is no room on the right

4 Wrapping around: the circular queue

The answer is to treat the array as a ring. After the last index comes index 0 again, the way 1 o'clock comes after 12. This is a circular buffer, and a queue on one is a circular queue.

We keep front, the index of the oldest value, and size. Every position comes from them with %, the remainder. With a capacity of 4, % 4 turns 4 into 0, and that is the wrap:

  • A new value goes to (front + size) % capacity.
  • The rear, the newest value, is at (front + size - 1) % capacity.
  • A dequeue moves the front on: front = (front + 1) % capacity.

Here is the queue from the last section, and what comes next:

A circular queue of 4
3081523frontrear
Add 3, 8, 5 at indexes 0, 1, 2
0front3size

The table shows the same run, with one more call: adding 9 to the full ring.

CallWhat it doesfrontsizeQueue, oldest first
enQueue(3)writes index 0013
enQueue(8)writes index 1023, 8
enQueue(5)writes index 2033, 8, 5
deQueue()front 0 → 1128, 5
deQueue()front 1 → 2215
enQueue(1)writes (2 + 1) % 4 = 3225, 1
enQueue(6)writes (2 + 2) % 4 = 0235, 1, 6
enQueue(7)writes (2 + 3) % 4 = 1245, 1, 6, 7
enQueue(9)full: false245, 1, 6, 7
deQueue()front 2 → 3331, 6, 7
deQueue()front (3 + 1) % 4 = 0026, 7

No value ever moved; only front and size changed. At the end, the front is data[0] = 6, and the rear is data[(0 + 2 - 1) % 4] = 7.

We could keep a rear index instead of size. But then a full ring and an empty ring look the same, with the rear just behind the front. size tells them apart.

C++

The library's queue is not one ring. It sits on a deque, which keeps values in small blocks and adds a block at either end. Each push and pop is still O(1).

ArrayDeque is this ring. It is a circular buffer that doubles its array when full, so it never refuses a value.

collections.deque is not one ring. It keeps values in linked blocks, but adding and removing at either end is still O(1).

There is no queue type. This ring, or an array with a front index, is how JavaScript code gets an O(1) dequeue.

There is no queue type. A slice with queue = queue[1:] drops the front in O(1). This ring is for when the size is fixed.

VecDeque is this ring. It is a circular buffer that grows when full, so it never refuses a value.

Queue<T> is this ring. It is a circular buffer that grows when full, so it never refuses a value.

Every method is a few steps, so each one is O(1), and the queue takes O(k) space.

A deque, a double-ended queue, also adds at the front and removes at the rear. On the same ring, adding at the front moves front back one place: (front - 1 + capacity) % capacity. The + capacity matters, because in most languages −1 % 4 is −1, not 3.

5 Stacks and queues on a linked list

A linked list has no capacity, and a change at the head is O(1). That is enough for both:

  • A stack. The head is the top. A push inserts a new head, and a pop moves the head on.
  • A queue. Values leave at the head and join at the tail. So we keep a tail pointer as well as head.
5top83
A stack after pushing 3, 8, 5
3head85tail
A queue after adding 3, 8, 5

Values cannot leave at the tail. Removing the tail needs the node before it, and that is an O(n) walk. Adding after the tail needs only the tail.

enqueue(x):  node = new Node(x)
             if tail is null:  head = node
             else:             tail.next = node
             tail = node

dequeue():   if head is null: empty
             x = head.val
             head = head.next
             if head is null: tail = null
             return x

Students miss the last if in dequeue. When the last value leaves, tail must become null too. Otherwise the next enqueue links onto the removed node.

Circular arrayLinked list
Each operationO(1)O(1)
SizeFixed capacityGrows freely
Extra memoryUnused slotsA next per value

The array is usually faster in practice, because its values sit together in memory.

6 A queue from two stacks

Some problems ask us to build one structure from the other. The classic is a queue from two stacks, and it comes from the plates. When we move a pile of plates, one at a time, onto a second pile, the bottom plate ends up on top.

So we keep two stacks. inbox takes every new value, and outbox hands values back. When a value is wanted and outbox is empty, we pour all of inbox into outbox. The oldest value lands on top. The shaded box is each stack's top:

A queue from two stacks
3081523
inbox: push 3, 8, 5
0123
outbox: empty

Pour only when outbox is empty. An early pour puts newer values on top of older ones. Push 3 and 8, pop (3), push 5, pop: the answer is 8, but an early pour returns 5.

One pop can be slow: step 2 moved three values. But each value is pushed onto inbox once, moved once, and popped from outbox once. So n operations take about 3n steps in all. This is amortised O(1): one call can cost O(n), but the average stays O(1). A dynamic array's push is amortised O(1) for the same reason.

The reverse, a stack from queues, has no such saving. A queue hands back only its oldest value, so to reach the newest, the others must pass through again. Either push or pop costs O(n).

7 Matching brackets with a stack

Stacks turn up wherever the newest unfinished thing must be handled first:

  • The back button. The browser goes back to the page we visited last.
  • Function calls. Each call waits for the call it made to finish. This is the call stack from the recursion lesson.
  • Matching brackets. A closing bracket must match the newest bracket still open.

Queues turn up where things wait their turn. Breadth-first search, in a later lesson, explores a graph with one.

In {[]()}, each opening bracket is a plate we put down. A closing bracket must match the plate on top, and then that plate comes off. At the end, the pile must be empty.

Checking {[]()}
{0[1]2(3)4}5i
{ opens: push it
{012
stack

A string can fail in three ways:

  • ([)]. At ), the top is [. That is the wrong match, so the answer is false.
  • ((). The string ends with ( still on the stack. Something never closed.
  • ()). At the last ), the stack is empty. A pop here would fail, so the code checks first.

C++

top() reads, pop() removes. pop() returns nothing, so read the top first. On an empty stack, both are undefined behaviour: the code may crash or carry on with a garbage value.

ArrayDeque, not Stack. The old Stack class still works, but it is slower and also lets code read the middle. pop() on an empty ArrayDeque throws an exception.

A list for a stack, deque for a queue. append and pop() at the end are O(1). pop(0) takes from the front and shifts every value, so it is O(n). Popping an empty list raises IndexError.

An array for a stack. push and pop are O(1). pop() on an empty array returns undefined with no error, so the check for empty matters even more.

A slice for a stack. append pushes, and stack[:len(stack)-1] pops. Reading the top of an empty slice stops the program with a Runtime Error.

A Vec for a stack. pop() returns an Option, so an empty stack gives None and the match handles it.

Stack<T> for a stack. Pop() and Peek() on an empty stack throw an exception, so check Count first.

Each character is pushed or popped at most once, so the check is O(n). The stack can hold up to n characters, so it takes O(n) space.

8 Mistakes, and what the problems need

  • Pop or peek on empty. On ()), the last ) finds an empty stack. Without the check, the pop is a Runtime Error in most languages.
  • The front of a dynamic array as a queue. v.erase(v.begin()) shifts every value, so 10⁵ values get TLE.
  • The rear off by one. (front + size) % capacity is the slot after the rear. On the full ring [6, 7, 5, 1] with front 2, it gives 5 instead of 7.
  • No full check. enQueue(9) on that ring writes to (2 + 4) % 4 = 2, over 5, the oldest value.
  • A negative index in a deque. front - 1 is −1 when front is 0. Add capacity before the %.
  • The tail left behind. Enqueue 3, dequeue, enqueue 8. Without tail = null, the 8 hangs off the removed node, and the queue looks empty.

The problems in this subtopic ask us to build a stack or a queue, on an array, on a linked list, or from the other one. Each needs only the pieces above: an index or a pointer for each end, % for the ring, and a check for empty before every read. Later lessons in this topic use a stack to evaluate expressions and to find the next greater value.

Before picking an operation, ask which end it touches. The end of an array and both ends of a deque are O(1). The front of an array is not.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.