Simple Algorithm
Algorithms & Data Structures · Brute Force · 16 min

Arrays, Linked Lists, Stacks & Queues

The building blocks every other data structure is made of.

Python fetches the millionth element of a list as fast as the first, yet inserting one item at the front of that list moves a million others. Every data structure is a trade-off like this one, and all of them are built from two raw materials: blocks of consecutive memory cells, and pointers from one cell to another.

What you’ll learn

  • Explain why reading a[i]a[i] from an array takes O(1)O(1) time while inserting in the middle takes O(n)O(n).
  • Describe how a dynamic array grows by doubling, and why an append costs O(1)O(1) amortized.
  • Insert and delete in a linked list by rewiring pointers, and say what the list gives up in exchange.
  • Trace a stack (last in, first out) and a queue (first in, first out), and name problems each one solves.
  • Choose a linear structure from the operations a problem needs most.

Memory is a row of numbered cells

Picture your computer's memory as one enormously long row of numbered cells, each holding one byte. A cell's number is its address. An array stores its elements side by side in one block of contiguous memory, and every element takes the same number of bytes, ss. If the block starts at address base\text{base}, element a[i]a[i] starts at

address(a[i])=base+i⋅s\text{address}(a[i]) = \text{base} + i \cdot s
One multiplication and one addition, whether the array holds ten elements or ten billion. That is random access in constant time, O(1)O(1).
Predict before you look

An array of 8-byte integers starts at address 1000. At which address does a[25]a[25] start?

Show the answer

1200

1000+25×8=12001000 + 25 \times 8 = 1200. Arrays count from 0: a[0]a[0] sits at the base itself, so a[25]a[25] is the 26th element. Counting from 0 is exactly what keeps the formula this simple.

The price of packing elements tightly shows up when you insert. To put 5 at index 1 of [3,7,1,9,4][3, 7, 1, 9, 4], every element from index 1 on must move one cell to the right, starting with the last so that nothing is overwritten:

StepCells 0 to 5
start, with one free cell at the end3 7 1 9 4 ·
move the 43 7 1 9 · 4
move the 93 7 1 · 9 4
move the 13 7 · 1 9 4
move the 73 · 7 1 9 4
write the 53 5 7 1 9 4
Inserting at index ii of nn elements moves n−in - i of them, and inserting at the front moves all nn. Deleting shifts the other way. Both cost O(n)O(n) in the worst case.

Spot it: a problem that keeps asking for "the element at position ii", or that scans everything in order while the elements rarely move, wants an array.

Growing an array: the doubling trick

A plain array cannot grow in place: the cells just past its end may already belong to something else. To make room you must allocate a bigger block elsewhere, copy every element over, and free the old block.

A dynamic array hides this behind one operation, append. It keeps spare room, so its capacity (slots allocated) can exceed its size (slots used), and it copies only when it is full. The only question is how much bigger the new block should be.

Why below 3? With doubling, a copy happens only when the size reaches 1,2,4,8,…1, 2, 4, 8, \dots, and each copy is twice as big as the one before. The largest copy, 2k2^k elements, is smaller than nn, so all the copies together come to less than 2n2n, and with the nn writes the total stays below 3n3n:

1+2+4+⋯+2k  <  2k+1  <  2n.1 + 2 + 4 + \dots + 2^k \;<\; 2^{k+1} \;<\; 2n.

So an append costs O(1)O(1) on average over any sequence of appends, even though the append that triggers a resize copies everything. A guarantee of this kind is called amortized. Python's list, C++'s std::vector and Java's ArrayList all grow this way, by a constant factor somewhere between about 1.125 and 2, depending on the library.

Think first Why not grow by a big fixed amount instead, say 1,000 slots at a time?

It only postpones the problem. Every 1,000 appends the whole array is still copied, so nn appends copy about n2/2000n^2/2000 elements: still quadratic, just a thousand times smaller. Growing by 10 slots at a time, 1,000 appends cost 50,600 in the same cost model, against 2,023 for doubling. Only multiplying the capacity keeps the total copying proportional to nn.

Spot it: collecting an unknown number of items one at a time means appending to a dynamic array. Inserting at the front again and again is the trap: every insert shifts everything.

Linked lists: boxes and arrows

A linked list makes the opposite trade. Each element lives in its own node, anywhere in memory, together with a pointer: the address of the next node. The list itself is just a pointer to the first node, the head, and the last node's pointer is null, drawn ∅.

To insert a new node x after a node p that you already hold, write two pointers: first x.next = p.next, then p.next = x. Nothing shifts, so this costs O(1)O(1) however long the list is. Deleting the node after p is a single write: p.next = p.next.next.

The price is random access. No formula gives the address of the ii-th node: you must follow ii pointers from the head, O(i)O(i) time, and each hop may land anywhere in memory, which real processors handle far more slowly than a walk through consecutive cells. A doubly linked list also stores in each node a pointer to the previous node, and keeps a tail pointer; then it adds or removes at both ends, and deletes any node it holds, in O(1)O(1), at the cost of an extra pointer per node.

Spot it: many insertions and deletions at places you already hold, such as the order of recently used items in a cache, and little need to jump to position ii.

Check your understanding

A singly linked list of nn nodes has only a head pointer. Which operation takes O(1)O(1) time?

  1. Reading the element at index 500
  2. Inserting a new first node
  3. Appending a new last node
  4. Deleting the last node
Show the answer

B. Inserting a new first node

A new first node needs two pointer writes, x.next = head and then head = x, whatever nn is. The other three must walk from the head: 500 hops to read index 500, n−1n - 1 hops to find the last node, and n−2n - 2 hops to find the node before the last one, whose pointer must become ∅.

Stacks: last in, first out

Many problems need far less than "any position". A stack lets you touch only one end, the top: push(x) puts xx on top and pop() removes the item on top. The last item in is the first out (LIFO), as with a pile of plates. Both operations cost O(1)O(1), on a dynamic array (top at the end) or on a linked list (top at the head).

Stacks appear wherever the most recent thing must be dealt with first:

  • Undo. Each edit is pushed; undo pops the most recent one.
  • The call stack. Each function call pushes a frame holding its local variables, and each return pops it. A recursion that never stops runs out of room: a stack overflow.
  • Matching brackets. In {[()]} every closing bracket must match the most recent opening bracket that is still unmatched, which is exactly the one on top of a stack.

Spot it: nesting (brackets, tags, folders inside folders), "undo the most recent", or a recursion you want to run without recursive calls.

Queues and deques: first in, first out

A queue adds at the back and removes from the front: the first item in is the first out (FIFO), as in a line at a ticket counter. A shared printer prints jobs in the order they were sent, a web server answers requests in the order they arrived, and breadth-first search explores a graph ring by ring by keeping its frontier in a queue.

Keeping a queue in an array with its front at index 0 would shift every item on each removal, O(n)O(n). The fix is to leave the items where they are and move the ends instead: a circular buffer keeps the index of the front item (head) and of the next free slot (tail), and both wrap around from the last slot to slot 0, as if the array were a ring.

A deque (a double-ended queue, pronounced "deck") adds and removes at both ends in O(1)O(1). In Python, collections.deque is the queue to use. A list is not, because list.pop(0) shifts every remaining item.

Spot it: "in the order they arrived", a waiting line, fairness, or the fewest steps from a starting point (breadth-first search) call for a queue; work at both ends calls for a deque.

A stack that keeps only what matters

Stacks also power some surprisingly fast algorithms. Take a row of numbers, daily temperatures say, and ask for each one: what is the next larger number to its right? That is its next greater element. The obvious method scans forward from every position, up to n−1n - 1 comparisons each, so O(n2)O(n^2) in total.

A monotonic stack answers every position in one pass. Walk left to right, keeping on a stack the positions still waiting for a larger number. When a new number arrives, it is the answer for every waiting number on top that is smaller: pop each of those and record the answer, then push the newcomer, which now waits too.

Think first A single arrival can pop many waiting numbers. Why is the whole scan still O(n)O(n)?

Count each position's life instead of each step: every position is pushed exactly once and popped at most once. So nn numbers cause at most nn pushes and nn pops in total, however they are spread out; here the 9 numbers cause 9 pushes and 6 pops. The Optimized lesson Monotonic Stacks & Queues turns this idea into sliding-window maxima, trapped rain water and the largest rectangle under a histogram.

Spot it: "for each element, the next (or previous) larger or smaller one", or "how many days until a warmer day", with nn too large for an O(n2)O(n^2) scan.

Choosing the right structure

StructureRead the ii-th itemAdd or remove at an endAdd or remove in the middle
Array (fixed size)O(1)O(1)not possible: the size is fixedO(n)O(n): shift the rest
Dynamic arrayO(1)O(1)at the end O(1)O(1) amortized; at the front O(n)O(n)O(n)O(n)
Singly linked list, head pointer onlyO(i)O(i): follow ii pointersat the head O(1)O(1); at the tail O(n)O(n)O(1)O(1) after a node you hold
Doubly linked list, head and tailO(i)O(i)O(1)O(1) at both endsO(1)O(1) at a node you hold
Stackonly the toppush and pop at the top: O(1)O(1)not allowed
Queue, dequeonly the endsO(1)O(1) at the allowed endsnot allowed
Stacks, queues and deques cost O(1)O(1) per operation in the worst case on a linked list, and O(1)O(1) amortized on a growable array, which is usually faster in practice. Finding a value takes O(n)O(n) in every row, unless the data is sorted.
Check your understanding

Match each job to a structure: (1) an editor's undo history; (2) print jobs sent to a shared office printer; (3) a game leaderboard that must show the player at any given rank instantly.

  1. (1) queue, (2) stack, (3) linked list
  2. (1) stack, (2) queue, (3) linked list
  3. (1) queue, (2) queue, (3) array
  4. (1) stack, (2) queue, (3) array
Show the answer

D. (1) stack, (2) queue, (3) array

Undo reverses the most recent edit first: last in, first out, a stack. The printer should serve the oldest job first: first in, first out, a queue. Showing rank rr instantly means reading index rr, which an array does in O(1)O(1).

Optimized lessonWhat you will do there
Arrays & Dynamic ArraysProve that doubling gives O(1)O(1) amortized appends, weigh growth factors such as 1.5 and 2, and master 2-D arrays, in-place rotation and the classic array bugs.
Linked ListsReverse a list in place, find its middle and detect a cycle with fast and slow pointers, and build an LRU cache from a hash map and a doubly linked list.
Stacks, Queues & DequesImplement each one, prove bracket matching correct with an invariant, run BFS with a queue and DFS with an explicit stack, and pick the right container in Python and C++.
Monotonic Stacks & QueuesFind next greater elements, sliding-window maxima, trapped rain water and the largest rectangle under a histogram, each in O(n)O(n).
Beyond them, the Optimal lessons explain why arrays beat pointers on real hardware (caches and external memory), squeeze bit vectors close to their information-theoretic minimum, and cover cycle detection, skip lists, persistent and lock-free structures, and expression parsing.

Key takeaways

  • An array is one contiguous block, so a[i]a[i] is a single address computation, O(1)O(1); inserting or deleting in the middle shifts the elements after it, O(n)O(n).
  • A dynamic array multiplies its capacity when it is full; copies at sizes 1,2,4,…1, 2, 4, \dots add up to less than 2n2n, so appends cost O(1)O(1) amortized. Python's list, C++'s std::vector and Java's ArrayList work this way.
  • A linked list stores each element in a node with a pointer to the next: inserting or deleting at a node you hold costs O(1)O(1), but reaching index ii takes ii hops.
  • A stack is last in, first out (undo, the call stack, bracket matching); a queue is first in, first out (waiting lines, breadth-first search); a deque works at both ends. Each operation costs O(1)O(1).
  • Choose by the operation you need most: positions → array; splicing at known places → linked list; most recent first → stack; arrival order → queue; the next greater or smaller element → monotonic stack.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

An array and a singly linked list hold the same million numbers. What does it take to read the element at index 500,000?

  1. One address computation in both
  2. About 500,000 steps in both
  3. One address computation in the array, and about 500,000 pointer hops in the list
  4. About 500,000 steps in the array, and one hop in the list
Show the answer

C. One address computation in the array, and about 500,000 pointer hops in the list

The array's elements are evenly spaced, so the address is base+500,000⋅s\text{base} + 500{,}000 \cdot s. The list's nodes can be anywhere, and the only way to find node 500,000 is to follow 500,000 pointers from the head.

Question 2

A dynamic array doubles its capacity whenever it is full. Which statement about appending a million items is true?

  1. Every append costs O(1)O(1) in the worst case
  2. Each resize copies everything, so the total work is Θ(n2)\Theta(n^2)
  3. Each append costs O(log⁡n)O(\log n), one unit for every doubling so far
  4. Most appends cost O(1)O(1), a few copy the whole array, and the total work is O(n)O(n)
Show the answer

D. Most appends cost O(1)O(1), a few copy the whole array, and the total work is O(n)O(n)

Resizes happen only at sizes 1,2,4,8,…1, 2, 4, 8, \dots, so the copies add up to less than 2n2n and the total stays below 3n3n: O(1)O(1) amortized per append. The append that triggers a resize still copies the whole array.

Question 3

To insert node x after node p in a singly linked list, a programmer writes p.next = x first and then x.next = p.next. What happens?

  1. x points to itself, and every node that came after p is lost
  2. The insertion works: the order of the two writes does not matter
  3. x ends up before p instead of after it
  4. Nothing changes, because x.next is written last
Show the answer

A. x points to itself, and every node that came after p is lost

After p.next = x, the expression p.next is x, so the second write sets x.next = x: a loop of one node. The only pointer to the rest of the list was overwritten, so those nodes can no longer be reached. Save the rest first: x.next = p.next, then p.next = x.

Question 4

A stack and a queue receive the same operations: add 1, add 2, add 3, remove, add 4, remove, remove. Which items come out, in order?

  1. Stack: 3, 2, 1; queue: 1, 2, 3
  2. Stack: 1, 2, 3; queue: 3, 4, 2
  3. Stack: 3, 4, 2; queue: 1, 2, 3
  4. Stack: 3, 4, 2; queue: 1, 2, 4
Show the answer

C. Stack: 3, 4, 2; queue: 1, 2, 3

The stack always removes the newest item: 3; then 4, added just before; then 2. The queue always removes the oldest: 1, then 2, then 3, while the 4 waits at the back.

Question 5

A queue lives in a circular buffer with 8 slots, numbered 0 to 7. The front item is in slot 6, and the queue holds 3 items. Which slot does the next enqueue fill?

  1. Slot 9
  2. Slot 1
  3. Slot 3
  4. Slot 0
Show the answer

B. Slot 1

The 3 items occupy slots 6, 7 and 0: after slot 7 the buffer wraps around to slot 0. The next free slot is (6+3) mod 8=1(6 + 3) \bmod 8 = 1.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 10 (elementary data structures) and section 16.4 (dynamic tables).
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 1.3 (bags, queues and stacks).