Arrays, Lists, Stacks, Queues, Hashing
The containers every other algorithm is built from, and why hashing makes lookups so fast.
- explain why list indexing is O(1) and inserting in the middle is O(n)
- build and traverse a linked list
- use stacks and queues and know their cost
- trace insertion into a hash table with linear probing and chaining
Arrays and Python lists
An array is a block of memory holding items of the same size, one after another. Because item i lives at start + i Γ size, the computer jumps straight to it: access by index is O(1). The price is rigidity: inserting in the middle means shifting everything after it.
A Python list looks like an array but is more flexible: it can hold items of different types and grow. Underneath, it is a dynamic array that keeps some spare room, so append is cheap on average.
| Operation on a list of n items | Cost |
|---|---|
L[i] read / write | O(1) |
L.append(x) | O(1) amortised |
L.pop() (last item) | O(1) |
L.insert(0, x) / L.pop(0) | O(n) β everything shifts |
x in L | O(n) |
L[a:b] slice | O(b β a) β makes a copy |
When the hidden array is full, Python allocates a bigger one (roughly 1.125Γ larger) and copies. That copy is expensive, but it happens rarely; spread over many appends the average cost per append stays constant.
Two lists, one object
Assignment of a list does not copy it β it makes a second name for the same object. This is behind many bugs.
What does this program print?
A = [1, 2, 3] B = A B.append(4) C = A[:] C.append(5) print(A, B, C)
Matrices: a classic trap
What does this program print?
bad = [[0] * 3] * 2 bad[0][1] = 9 good = [[0] * 3 for _ in range(2)] good[0][1] = 9 print(bad) print(good)
Why is L.pop(0) slower than L.pop() on a long list?
Linked lists
To avoid shifting, store each item in its own node that also holds a reference to the next node. Insertion or deletion at a known position is then O(1) β just rewire a pointer. The price: no direct access to item i; you must walk from the head, which is O(i).
| Array / list | Linked list | |
|---|---|---|
| Access item i | O(1) | O(i) |
| Insert / delete at front | O(n) | O(1) |
| Insert after a known node | O(n) | O(1) |
| Memory per item | just the value | value + reference |
Which operation is O(1) for a singly linked list (only a head reference kept) but O(n) for an array-based list?
What does this print?
class Node:
def __init__(self, v, nxt=None):
self.v, self.next = v, nxt
head = Node(1, Node(2, Node(3)))
cur, total = head, 0
while cur:
total = total * 10 + cur.v
cur = cur.next
print(total)Stacks: last in, first out
A stack supports push(x) (add on top) and pop() (remove the top). Think of a pile of plates. Both operations are O(1). In Python, a list used from its right end works perfectly: append to push, pop() to pop.
- Function calls (the call stack) and recursion
- Undo / back-button history
- Matching brackets and evaluating expressions
- Depth-first search (Week 4)
This evaluates a postfix expression. What is printed?
st = []
for token in "3 4 + 2 *".split():
if token in "+*":
b, a = st.pop(), st.pop()
st.append(a + b if token == "+" else a * b)
else:
st.append(int(token))
print(st)Pushing 1, 2, 3 then popping once returnsβ¦
Queues: first in, first out
A queue supports enqueue(x) at the back and dequeue() from the front, like a line at a counter. With a plain Python list, pop(0) costs O(n) β so use collections.deque, where both ends are O(1). (You can also keep a list plus a moving 'front' index.)
A breadth-first search needs which structure to hold 'places still to visit'?
What does this program print?
from collections import deque q = deque([1, 2, 3]) q.append(q.popleft()) q.append(4) print(list(q))
Dictionaries and hashing
Searching an unsorted list is O(n); a sorted list gives O(log n) but makes inserts slow. Can we get O(1) on average for lookup, insert and delete? Yes β with a hash table. Python's dict and set are hash tables.
The idea
Keep an array of m slots. A hash function h(key) turns a key into a slot number between 0 and mβ1; store the key there. To look up a key, compute h(key) and check that slot β no scanning. A simple choice for integers is h(x) = x mod m.
Collisions
Different keys can land in the same slot (a collision) β inevitable, since there are many more possible keys than slots. Two main strategies:
| Strategy | How it resolves collisions |
|---|---|
| Open addressing | Look for another free slot by a fixed rule β linear probing tries h, h+1, h+2, β¦ ; quadratic probing tries h, h+1Β², h+2Β², β¦ |
| Chaining | Each slot holds a list of all keys that hash there |
With n keys in m slots, the load factor is Ξ± = n / m. Chaining keeps chains of expected length Ξ±; open addressing degrades sharply as Ξ± β 1 and fails when the table is full. Real tables resize (typically doubling and rehashing) to keep Ξ± below about 2/3.
You cannot simply empty a slot: later keys that probed past it would become unreachable. Mark it as a deleted tombstone instead.
Linear probing, m = 7. What is the final table?
m = 7
T = [None] * m
for k in [10, 17, 24, 3]:
i = k % m
while T[i] is not None:
i = (i + 1) % m
T[i] = k
print(T)What is the main weakness of linear probing?
Which keys can a Python dict use?
Using dictionaries: counting and grouping
The two-sum program above runs inβ¦
Chapter challenge β Week 3
Which structure gives O(1) average time to check 'is this value present?'
What does this program print?
st = []
for ch in "abc":
st.append(ch)
out = ""
while st:
out += st.pop()
print(out)What does this program print?
from collections import deque
q = deque()
for x in [1, 2, 3, 4]:
q.append(x)
if x % 2 == 0:
q.popleft()
print(list(q))Insert key 23 into a table (m = 10) with linear probing.
Using h(x) = x mod 11, which slot does key 100 go to (if empty)?
Select the true statements about linked lists.
A hash table with load factor Ξ± = 0.5 using chaining has an expected chain length ofβ¦
Which pair correctly matches structure and discipline?
Practice on LeetCode
Lists, linked lists, stacks, queues and hash tables.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Two Sum β | Easy | dictionary lookup for the complement: O(n) | |
| Contains Duplicate β | Easy | a set | |
| Valid Anagram β | Easy | counting with a dictionary | |
| Group Anagrams β | Medium | a hash table keyed by a canonical form | |
| Design HashMap β | Easy | build your own hash table with chaining | |
| Reverse Linked List β | Easy | pointer rewiring | |
| Linked List Cycle β | Easy | fast and slow pointers | |
| Merge Two Sorted Lists β | Easy | linked-list merge | |
| Valid Parentheses β | Easy | a stack | |
| Min Stack β | Medium | stack with an extra O(1) query | |
| Implement Queue using Stacks β | Easy | FIFO from two LIFOs | |
| Evaluate Reverse Polish Notation β | Medium | the postfix evaluator from this chapter | |
| Daily Temperatures β | Medium | monotonic stack |
Key takeaways
- Arrays give O(1) indexing, but inserting or deleting in the middle shifts items; Python lists append in amortised O(1).
- Linked lists make local insert/delete O(1) but give up O(1) access.
- A stack is LIFO (push/pop); a queue is FIFO (enqueue/dequeue) β use
dequefor O(1) at both ends. - Hash tables give O(1) average lookup/insert/delete; collisions are resolved by probing or chaining, and the load factor must stay small.
- Beware aliasing:
B = Ashares a list, and[[0]*3]*2shares rows.