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 from an array takes time while inserting in the middle takes .
- Describe how a dynamic array grows by doubling, and why an append costs 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, . If the block starts at address , element starts at
An array of 8-byte integers starts at address 1000. At which address does start?
Show the answer
1200
. Arrays count from 0: sits at the base itself, so 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 , every element from index 1 on must move one cell to the right, starting with the last so that nothing is overwritten:
| Step | Cells 0 to 5 |
|---|---|
| start, with one free cell at the end | 3 7 1 9 4 · |
| move the 4 | 3 7 1 9 · 4 |
| move the 9 | 3 7 1 · 9 4 |
| move the 1 | 3 7 · 1 9 4 |
| move the 7 | 3 · 7 1 9 4 |
| write the 5 | 3 5 7 1 9 4 |
Spot it: a problem that keeps asking for "the element at position ", 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 , and each copy is twice as big as the one before. The largest copy, elements, is smaller than , so all the copies together come to less than , and with the writes the total stays below :
So an append costs 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 appends copy about 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 .
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 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 -th node: you must follow pointers from the head, 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 , 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 .
A singly linked list of nodes has only a head pointer. Which operation takes time?
- Reading the element at index 500
- Inserting a new first node
- Appending a new last node
- 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 is. The other three must walk from the head: 500 hops to read index 500, hops to find the last node, and 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 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 , 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, . 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 . 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 comparisons each, so 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 ?
Count each position's life instead of each step: every position is pushed exactly once and popped at most once. So numbers cause at most pushes and 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 too large for an scan.
Choosing the right structure
| Structure | Read the -th item | Add or remove at an end | Add or remove in the middle |
|---|---|---|---|
| Array (fixed size) | not possible: the size is fixed | : shift the rest | |
| Dynamic array | at the end amortized; at the front | ||
| Singly linked list, head pointer only | : follow pointers | at the head ; at the tail | after a node you hold |
| Doubly linked list, head and tail | at both ends | at a node you hold | |
| Stack | only the top | push and pop at the top: | not allowed |
| Queue, deque | only the ends | at the allowed ends | not allowed |
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) queue, (2) stack, (3) linked list
- (1) stack, (2) queue, (3) linked list
- (1) queue, (2) queue, (3) array
- (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 instantly means reading index , which an array does in .
| Optimized lesson | What you will do there |
|---|---|
| Arrays & Dynamic Arrays | Prove that doubling gives 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 Lists | Reverse 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 & Deques | Implement 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 & Queues | Find next greater elements, sliding-window maxima, trapped rain water and the largest rectangle under a histogram, each in . |
Key takeaways
- An array is one contiguous block, so is a single address computation, ; inserting or deleting in the middle shifts the elements after it, .
- A dynamic array multiplies its capacity when it is full; copies at sizes add up to less than , so appends cost amortized. Python's
list, C++'sstd::vectorand Java'sArrayListwork 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 , but reaching index takes 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 .
- 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.
An array and a singly linked list hold the same million numbers. What does it take to read the element at index 500,000?
- One address computation in both
- About 500,000 steps in both
- One address computation in the array, and about 500,000 pointer hops in the list
- 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 . 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.
A dynamic array doubles its capacity whenever it is full. Which statement about appending a million items is true?
- Every append costs in the worst case
- Each resize copies everything, so the total work is
- Each append costs , one unit for every doubling so far
- Most appends cost , a few copy the whole array, and the total work is
Show the answer
D. Most appends cost , a few copy the whole array, and the total work is
Resizes happen only at sizes , so the copies add up to less than and the total stays below : amortized per append. The append that triggers a resize still copies the whole array.
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?
xpoints to itself, and every node that came afterpis lost- The insertion works: the order of the two writes does not matter
xends up beforepinstead of after it- Nothing changes, because
x.nextis 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.
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?
- Stack: 3, 2, 1; queue: 1, 2, 3
- Stack: 1, 2, 3; queue: 3, 4, 2
- Stack: 3, 4, 2; queue: 1, 2, 3
- 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.
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?
- Slot 9
- Slot 1
- Slot 3
- 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 .
Go deeper
- Arrays & Dynamic Arrays · Contiguous memory, constant-time indexing and the doubling trick.
- Linked Lists · Nodes and pointers: cheap splicing, no random access.
- Stacks, Queues & Deques · Last in, first out; first in, first out; and both ends at once.
- Monotonic Stacks & Queues · Next greater elements, sliding-window maxima and the largest rectangle, in linear time.
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).