Wiki
Core12 min read

Arrays, stacks and queues

A contiguous array with a discipline on top: LIFO for a stack, FIFO for a queue, and why the end is the cheap place to touch.

A Python list is an array: its elements sit next to each other in memory, so reaching index i is a predictable computation and costs O(1)O(1) no matter how long the list is. Almost every other structure in this chapter either extends that array or trades it away. Stacks and queues are the two simplest disciplines you can put on top of it.

One array, two rules

A stack says "the last thing in is the first thing out" — LIFO. A queue says "the first thing in is the first thing out" — FIFO. The storage is identical; only the rule for which end you remove from differs. That single choice changes which algorithms they suit.

Push, pop, enqueue and dequeue below and watch the same numbers leave in opposite orders.

Add the same numbers to both — then see which one comes back first

stack (LIFO)

empty stack

queue (FIFO)

frontempty queue
back

Last call: —. In an array both can be O(1) if you keep a top index or a front index — the discipline, not the operation, is what separates them. Use a stack for undo and recursion; a queue for scheduling and breadth-first search.

The cost of touching each end

For a Python list used as an array:

  • a[i] is O(1)O(1) — one address calculation.
  • a.append(x) is amortised O(1)O(1) — occasionally the array is full and must be reallocated and copied, but spread over many appends the average is constant.
  • a.pop() from the end is O(1)O(1).
  • a.pop(0) or a.insert(0, x) is O(n)O(n) — every other element must shift.

That last line is the reason a list is a fine stack but a poor queue: dequeuing from the front re-shuffles the whole array each time, making nn dequeues O(n2)O(n^2).

Queue done right

collections.deque is a doubly linked list of fixed-size blocks, so it offers O(1)O(1) append and pop at both ends:

from collections import deque
 
q = deque()
q.append("a")        # enqueue at the back
q.append("b")
first = q.popleft()  # dequeue from the front, O(1)

Use a deque whenever you need a queue; use a list when you need a stack or random access.

Where each is used

  • Stack: undo/redo, matching brackets, depth-first search, the function call stack itself.
  • Queue: task scheduling, buffering, breadth-first search, printer spools.

A Python list is a dynamic array, not a linked list

It looks like a list and grows without a declared size, but underneath it is a resizable contiguous buffer. That is why indexing is cheap and front insertion is expensive — the opposite profile from the linked lists in the next lesson.

Illustrative vs real

The simulator keeps a handful of integers on screen and mutates real arrays. Real programs may hold millions of records, and the constant factor of reallocation only becomes noticeable at that scale. The asymptotics — O(1)O(1) at the end, O(n)O(n) at the front, amortised growth — are what the panel is teaching.

Check yourself

Eduspheria wiki · Programming & Data Structures, Data structures

0 / 5 answered

  1. 1What is the complexity of inserting at the front of a Python list?
    Multiple choice
  2. 2A deque gives O(1) append and pop at both ends.
    True / false
  3. 3Which ordering discipline does a queue provide?
    Short answer
  4. 4Which operation is amortised O(1) on a Python list?
    Multiple choice
  5. 5Using a list as a queue and calling pop(0) n times, what is the total number of element shifts in the worst case for n = 10?
    shifts
    Numeric answer

From the exam paper

Modeled on NITJ AI-507, End-Sem December 2024

0 / 5 answered

  1. 1Starting from an empty stack, these operations run in order: push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop(). What is the sequence of values popped?
    Multiple choice
  2. 2After that whole series of stack operations finishes, how many values remain on the stack?
    values
    Numeric answer
  3. 3What is the postfix form of the infix expression ( AX * ( BX * ( ( ( CY + AY ) + BY ) * CX ) ) )?
    Multiple choice
  4. 4What is the prefix form of the infix expression ( AX * ( BX * ( ( ( CY + AY ) + BY ) * CX ) ) )?
    Multiple choice
  5. 5What is the postfix form of the infix expression ((H*((((A+((B+C)*D))*F)*G)*E))+J)?
    Multiple choice

Where next: linked lists — giving up cheap indexing to make insertion and deletion cheap anywhere.