PDSA Interactive Book
Week 3

Arrays, Lists, Stacks, Queues, Hashing

The containers every other algorithm is built from, and why hashing makes lookups so fast.

After this chapter you can…
  • 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 itemsCost
L[i] read / writeO(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 LO(n)
L[a:b] sliceO(b βˆ’ a) β€” makes a copy
Amortised O(1) append

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.

Python Β· editable

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.

Predict the output

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

Predict the output

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)
Check yourself

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).

Python Β· editable
Expected output: [9, 3, 4]
Linked list β€” insert and delete and watch the pointersInteractive
Array / listLinked list
Access item iO(1)O(i)
Insert / delete at frontO(n)O(1)
Insert after a known nodeO(n)O(1)
Memory per itemjust the valuevalue + reference
Check yourself

Which operation is O(1) for a singly linked list (only a head reference kept) but O(n) for an array-based list?

Predict the output

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.

Stack β€” push and popInteractive
Python Β· editable
Expected output: (a[b]{c}) True (] False ((a) False {[()]} True
Where stacks show up
  • Function calls (the call stack) and recursion
  • Undo / back-button history
  • Matching brackets and evaluating expressions
  • Depth-first search (Week 4)
Predict the output

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)
Check yourself

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.)

Queue β€” enqueue and dequeueInteractive
Python Β· editable
Expected output: A B ['C', 'D']
Check yourself

A breadth-first search needs which structure to hold 'places still to visit'?

Predict the output

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:

StrategyHow it resolves collisions
Open addressingLook for another free slot by a fixed rule β€” linear probing tries h, h+1, h+2, … ; quadratic probing tries h, h+1Β², h+2Β², …
ChainingEach slot holds a list of all keys that hash there
Hash table β€” insert keys and watch collisions get resolvedInteractive
Load factor lab β€” why hash tables must resizeInteractive
Python Β· editable
Expected output: 15 -> start slot 1 probes: 1 22 -> start slot 1 probes: 2 8 -> start slot 1 probes: 3 29 -> start slot 1 probes: 4 36 -> start slot 1 probes: 5 [None, 15, 22, 8, 29, 36, None]
Load factor

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.

Deleting in open addressing

You cannot simply empty a slot: later keys that probed past it would become unreachable. Mark it as a deleted tombstone instead.

Predict the output

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)
Check yourself

What is the main weakness of linear probing?

Check yourself

Which keys can a Python dict use?

Python Β· editable
Expected output: True True False False

Using dictionaries: counting and grouping

Python Β· editable
Expected output: {'to': 3, 'be': 3, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1} to (2, 3)
Check yourself

The two-sum program above runs in…

Chapter challenge β€” Week 3

…
Check yourself

Which structure gives O(1) average time to check 'is this value present?'

Predict the output

What does this program print?

st = []
for ch in "abc":
    st.append(ch)
out = ""
while st:
    out += st.pop()
print(out)
Predict the output

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))
Put in order

Insert key 23 into a table (m = 10) with linear probing.

Check yourself

Using h(x) = x mod 11, which slot does key 100 go to (if empty)?

Check yourself

Select the true statements about linked lists.

Check yourself

A hash table with load factor Ξ± = 0.5 using chaining has an expected chain length of…

Check yourself

Which pair correctly matches structure and discipline?

Practice on LeetCode

Lists, linked lists, stacks, queues and hash tables.

How to practise

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.

0 / 13 solvedTick a problem when you have solved it β€” saved in this browser.
ProblemLevelPractises
Two Sum β†—Easydictionary lookup for the complement: O(n)
Contains Duplicate β†—Easya set
Valid Anagram β†—Easycounting with a dictionary
Group Anagrams β†—Mediuma hash table keyed by a canonical form
Design HashMap β†—Easybuild your own hash table with chaining
Reverse Linked List β†—Easypointer rewiring
Linked List Cycle β†—Easyfast and slow pointers
Merge Two Sorted Lists β†—Easylinked-list merge
Valid Parentheses β†—Easya stack
Min Stack β†—Mediumstack with an extra O(1) query
Implement Queue using Stacks β†—EasyFIFO from two LIFOs
Evaluate Reverse Polish Notation β†—Mediumthe postfix evaluator from this chapter
Daily Temperatures β†—Mediummonotonic 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 deque for 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 = A shares a list, and [[0]*3]*2 shares rows.

PDSA Interactive Book Β· Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi Β· Β© 2026. An unofficial study companion β€” the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub β†— Β· Press / to search.