PDSA Interactive Book
Week 12

Summary & Final Review

One map of the whole course, a cheat sheet, and a final mixed test.

After this chapter you can…
  • see the whole course as a small set of reusable ideas
  • pick an algorithm or data structure from a problem statement
  • recall the main complexities
  • check yourself with a mixed final test

The whole course on one page

Twelve weeks, but only a handful of big ideas. Use this page as a map when you revise.

IdeaWhere you saw itCore cost
Count operations, ignore constantsWeek 1–2O, Ω, Θ
Halve the problembinary search, merge sort, fast power, quickselectlog n / n log n
Choose a clever data structurestack, queue, hash table, heap, BST, AVL, trie, union–findO(1) – O(log n) per operation
Explore a graphBFS, DFS, topological sortO(n + m)
Be greedy (with proof)Dijkstra, Kruskal, Prim, interval scheduling, Huffmanusually O(m log n) or O(n log n)
Remember subproblemsFibonacci, grid paths, LCS, edit distance, matrix chain, knapsack#subproblems × work each
Reduce one problem to anothermatching → flow, LP, NP-completenesspolynomial vs presumed exponential

Complexity cheat sheet

Sorting and searching

AlgorithmTimeNotes
Linear searchO(n)any list
Binary searchO(log n)sorted list
Selection / insertion / bubble sortO(n²)insertion: O(n) if already sorted
Merge sortΘ(n log n)O(n) extra space, stable
QuicksortO(n log n) average, O(n²) worstin place
Heap sortΘ(n log n)in place, not stable
QuickselectO(n) expectedmedian of medians: O(n) worst

Data structures

StructureSearchInsertDeleteNotes
Array / listO(n)O(n) middle, O(1) endO(n)O(1) index
Linked listO(n)O(1) at known placeO(1) at known place
Hash tableO(1) avgO(1) avgO(1) avgworst O(n)
Binary heapO(n)O(log n)O(log n) max/minpeek max O(1)
BSTO(h)O(h)O(h)h up to n
AVL treeO(log n)O(log n)O(log n)always balanced
TrieO(L)O(L)O(L)L = word length
Union–Findfind ≈ O(1)union ≈ O(1)—amortised α(n)

Graph algorithms (n vertices, m edges)

AlgorithmProblemTime
BFSreachability, fewest edgesO(n + m)
DFScomponents, cycles, orderingO(n + m)
Topological sortorder a DAGO(n + m)
Dijkstra (heap)shortest paths, weights ≥ 0O((n + m) log n)
Bellman–Fordshortest paths, negative edgesO(nm)
Floyd–Warshallall-pairs shortest pathsO(n³)
KruskalMSTO(m log m)
Prim (heap)MSTO(m log n)
Edmonds–Karpmaximum flowO(n·m²)

Strings and DP tables

AlgorithmTime
Brute-force matchingO(nm)
KMPO(n + m)
Boyer–Mooresub-linear typical
LCS / edit distanceO(mn)
Matrix chainO(n³)
0/1 knapsackO(nW)

Which technique? A decision guide

The problem says…Try…
sorted data, find an item or positionbinary search
'fewest steps / moves / edges'BFS
'is it reachable', 'how many groups', 'find a cycle'DFS / BFS / union–find
tasks with prerequisitestopological sort (DAG); longest path = critical path
cheapest route with positive weightsDijkstra
cheapest way to connect everythingMST (Kruskal / Prim)
always need the biggest / smallest nextheap (priority queue)
count distinct / 'have I seen it?'hash set / dict
maximum number of non-overlapping intervalsgreedy: sort by finish time
best over choices, overlapping subproblems, greedy failsdynamic programming
maximise throughput through a capacity network, matchingmax flow
find a pattern in a long textKMP / Boyer–Moore
every known algorithm is exponential, looks like SAT / TSP / subset sumNP-hardness: approximate or restrict
Which technique? Answer a few questions about the problemInteractive
A good habit

Before coding, estimate the cost: with n = 10⁵, an O(n²) plan is 10¹⁰ steps — too slow in Python. Ask whether sorting, a heap, a hash table or a different technique brings it to O(n log n).

Common mistakes to avoid

  • Running binary search on unsorted data.
  • Using list.pop(0) as a queue (O(n)) instead of deque.popleft().
  • Applying Dijkstra with negative edge weights.
  • Using greedy without a correctness argument (coin change!).
  • Writing [[0]*c]*r for a matrix — all rows are the same list.
  • Making two recursive calls where one would do (fast power).
  • Forgetting that a hash table's worst case is O(n), and that dictionary keys must be immutable.
  • Forgetting that BST height depends on insertion order.

Final test — mixed questions from all weeks

…
Check yourself

T(n) = 2T(n/2) + n. The solution is…

Predict the output

Selection sort stopped after two rounds. The list is…

L = [5, 2, 9, 1, 7]
for i in range(len(L) - 1):
    m = i
    for j in range(i + 1, len(L)):
        if L[j] < L[m]:
            m = j
    L[i], L[m] = L[m], L[i]
    if i == 1:
        break
print(L)
Check yourself

Which structure has O(1) average-time membership test?

Predict the output

What topological order does this print?

adj = {1: [2, 3], 2: [4], 3: [4], 4: [5], 5: []}
indeg = {v: 0 for v in adj}
for u in adj:
    for v in adj[u]:
        indeg[v] += 1
ready = [v for v in adj if indeg[v] == 0]
order = []
while ready:
    u = ready.pop(0)
    order.append(u)
    for v in adj[u]:
        indeg[v] -= 1
        if indeg[v] == 0:
            ready.append(v)
print(order)
Check yourself

Which algorithm solves single-source shortest paths when edges can be negative?

Check yourself

A min-heap holds 1,023 items. Roughly how many swaps may one insertion need at most?

Put in order

Match the algorithm to its first step — order Dijkstra's algorithm.

Check yourself

Which problems are solved by a greedy algorithm with a correctness proof?

Check yourself

Edit distance between 'cat' and 'cut'?

Predict the output

What does this print? (type the exact output)

def f(n):
    if n <= 1:
        return 1
    return f(n - 1) + f(n - 2)
print(f(6))
Check yourself

A text has length 10⁶ and a pattern has length 100. Which gives a worst-case guarantee of about 10⁶ steps?

Check yourself

You need the 3 largest of 10⁶ numbers. A good approach is…

Check yourself

Which is not known to be in P?

Predict the output

What does this print? (type the exact output)

from collections import deque
def bfs_dist(adj, s, t):
    d, q = {s: 0}, deque([s])
    while q:
        u = q.popleft()
        for v in adj[u]:
            if v not in d:
                d[v] = d[u] + 1
                q.append(v)
    return d[t]
adj = {0: [1, 2], 1: [3], 2: [3, 4], 3: [5], 4: [5], 5: []}
print(bfs_dist(adj, 0, 5))
Check yourself

Which of these guarantees O(log n) for every operation on n keys?

Practice on LeetCode

A mixed set that touches every part of the course — try to name the technique before you code.

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 / 12 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Two Sum ↗Easyhash table
Valid Parentheses ↗Easystack
Merge Intervals ↗Mediumsort + sweep
Number of Islands ↗MediumDFS / BFS / union–find
Course Schedule ↗Mediumtopological sort
Network Delay Time ↗MediumDijkstra
Kth Largest Element in an Array ↗Mediumheap or quickselect
Coin Change ↗Mediumdynamic programming
Longest Common Subsequence ↗Mediumdynamic programming on two strings
LRU Cache ↗Mediumhash table + linked list design
Implement Trie (Prefix Tree) ↗Mediumtrie
Min Cost to Connect All Points ↗MediumMST

Beyond LeetCode

Key takeaways

  • Always estimate cost first: counting operations and spotting n, n log n, n² or exponential growth tells you whether an approach will work.
  • Recognise the pattern: halving → log; sort first; graph exploration → BFS/DFS; greedy needs proof; overlapping subproblems → DP; capacities → flow.
  • Data structures are tools: pick one so the operation you repeat most often is cheap.
  • Some problems (NP-complete) have no known fast algorithm — recognise them, then approximate or restrict.

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.