IIT Madras Zanzibar · Teaching

← Z5007 Overview

Weeks 1–17 Code & Complexity Explorer

Searchable browser preview of all 17 weekly Z5007 Python reference modules and the Course Project benchmark starter, paired with Big-O complexity summaries, Colab links, and LaTeX cheat sheets.

Week 01O(1), O(log n), O(n), O(n log n), O(n^2)

Asymptotic Complexity & Log-Log Benchmarking

Reference Python implementation and self-checks for Z5007 Week 1.

Python Preview
import math
import random
import time
from typing import Callable


def constant_lookup(arr: list[int], index: int) -> tuple[int, int]:
    """Return (arr[index], step_count) in O(1) time."""
    if not 0 <= index < len(arr):
        raise IndexError("index out of range")
Week 02O(log n) search · O(n^2) Bubble/Selection

Arrays, Binary Search & Simple Sorts

Reference Python implementation and self-checks for Z5007 Week 2.

Python Preview
import random
from typing import Any, Optional


class StaticArray:
    """Fixed-capacity contiguous slot array supporting O(1) indexed access and O(n) shift edits."""

    def __init__(self, capacity: int) -> None:
        if capacity <= 0:
            raise ValueError("capacity must be positive")
Week 03O(n + I) adaptive sort · O(1) push/pop

Insertion Sort & Stacks (LIFO)

Reference Python implementation and self-checks for Z5007 Week 3.

Python Preview
from typing import Any, Optional


def insertion_sort(arr: list[Any]) -> tuple[int, int]:
    """In-place stable Insertion Sort returning (comparisons, shifts)."""
    comps = shifts = 0
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0:
Week 04O(1) deque & LRU get/put via dict + DLL

Circular Queues, Linked Lists & LRU Cache

Reference Python implementation and self-checks for Z5007 Week 4.

Python Preview
from typing import Any, Optional


class CircularArrayQueue:
    """FIFO queue using modular wrap-around indexing and amortized doubling."""

    def __init__(self, capacity: int = 8) -> None:
        self._data: list[Any] = [None] * capacity
        self._front = 0
        self._size = 0
Week 05O(n log n) Divide & Conquer · O(n) Quickselect

Recursion, Merge Sort & Randomized Quicksort

Reference Python implementation and self-checks for Z5007 Week 5.

Python Preview
import random


def merge_sort_and_count(arr: list[int]) -> tuple[list[int], int]:
    """Return (sorted_copy, inversion_count) in O(n log n) time."""
    if len(arr) <= 1:
        return arr[:], 0
    mid = len(arr) // 2
    left, inv_l = merge_sort_and_count(arr[:mid])
    right, inv_r = merge_sort_and_count(arr[mid:])
Week 06O(h) insert/search/delete · Pre/In/Post/BFS

Binary Trees, Traversals & BST Operations

Reference Python implementation and self-checks for Z5007 Week 6.

Python Preview
from collections import deque
import random
from typing import Any, Optional


class TreeNode:
    """Binary tree node storing a key and optional left/right children."""

    def __init__(self, key: Any, left: Optional[TreeNode] = None, right: Optional[TreeNode] = None) -> None:
        self.key = key
Week 07O(log n) worst-case height < 1.44 log2(n+2)

Self-Balancing AVL Trees (LL, RR, LR, RL)

Reference Python implementation and self-checks for Z5007 Week 7.

Python Preview
import math
import random
from typing import Any, Optional


class AVLNode:
    """Node of an AVL tree caching subtree height for O(1) balance factor checks."""

    def __init__(self, key: Any) -> None:
        self.key = key
Week 08O(n) Floyd heapify · Chaining vs Linear Probing

Binary Max-Heaps & Hash Tables

Reference Python implementation and self-checks for Z5007 Week 8.

Python Preview
import random
from typing import Any, Optional


class MaxHeap:
    """Array-backed binary max-heap with O(n) Floyd heapify and O(log n) push/pop."""

    def __init__(self, items: Optional[list[Any]] = None) -> None:
        self._a: list[Any] = list(items) if items else []
        if len(self._a) > 1:
Week 09O(V + E) shortest hops, timestamps & Kahn DAG

Graph Traversals: BFS, DFS & Topological Sort

Reference Python implementation and self-checks for Z5007 Week 9.

Python Preview
from collections import deque
from typing import Hashable


class Graph:
    """Adjacency-list graph supporting directed and undirected edges."""

    def __init__(self, directed: bool = False) -> None:
        self.directed = directed
        self.adj: dict[Hashable, list[Hashable]] = {}
Week 10Dijkstra O((V+E) log V) · Bellman-Ford O(VE)

Single-Source Shortest Paths

Reference Python implementation and self-checks for Z5007 Week 10.

Python Preview
import heapq
import math
from typing import Hashable


WeightedAdj = dict[Hashable, list[tuple[Hashable, float]]]


def dijkstra(adj: WeightedAdj, source: Hashable) -> tuple[dict[Hashable, float], dict[Hashable, Hashable | None]]:
    """Compute single-source shortest paths for non-negative edge weights in O((V + E) log V)."""
Week 11Kruskal & Prim O(E log V) · Interval Scheduling

Greedy Exchange & Minimum Spanning Trees

Reference Python implementation and self-checks for Z5007 Week 11.

Python Preview
import heapq
import random
from typing import Hashable


class DisjointSet:
    """Union-Find with path compression and union by rank."""

    def __init__(self, items: list[Hashable]) -> None:
        self.parent: dict[Hashable, Hashable] = {x: x for x in items}
Week 120/1 Knapsack O(nW) · LCS & Edit Distance O(mn)

Dynamic Programming Foundations

Reference Python implementation and self-checks for Z5007 Week 12.

Python Preview
from functools import lru_cache


def fib_memo(n: int) -> int:
    """Top-down memoized Fibonacci in O(n) time."""
    memo: dict[int, int] = {0: 0, 1: 1}

    def _f(k: int) -> int:
        if k not in memo:
            memo[k] = _f(k - 1) + _f(k - 2)
Week 13Matrix Chain O(n^3) · LIS O(n log n) · Held-Karp

Advanced Dynamic Programming

Reference Python implementation and self-checks for Z5007 Week 13.

Python Preview
import bisect
import math


def matrix_chain_order(dims: list[int]) -> tuple[int, str]:
    """Return (min_scalar_multiplications, optimal_parenthesization) for matrix chain dims."""
    n = len(dims) - 1
    dp = [[0] * n for _ in range(n)]
    split = [[0] * n for _ in range(n)]
    for length in range(2, n + 1):
Week 14KMP O(n + m) · Trie O(L) prefix lookup

String Matching (KMP, Rabin-Karp) & Tries

Reference Python implementation and self-checks for Z5007 Week 14.

Python Preview
class TrieNode:
    def __init__(self) -> None:
        self.children: dict[str, TrieNode] = {}
        self.is_end: bool = False


class PrefixTrie:
    """Prefix tree supporting O(L) insert, exact search, and prefix autocomplete."""

    def __init__(self) -> None:
Week 15Union by rank + path compression O(alpha(n))

Disjoint Set Union & Amortized Potential

Reference Python implementation and self-checks for Z5007 Week 15.

Python Preview
class DisjointSetUnion:
    """Union-Find with path compression and union by size/rank."""

    def __init__(self, n: int) -> None:
        self.parent = list(range(n))
        self.size = [1] * n
        self.components = n
        self.parent_hops = 0

    def find(self, x: int) -> int:
Week 163-SAT -> Independent Set · Vertex Cover 2-Approx

NP-Completeness, Reductions & 2-Approx

Reference Python implementation and self-checks for Z5007 Week 16.

Python Preview
from typing import Optional


def eval_cnf(clauses: list[tuple[int, ...]], assignment: dict[int, bool]) -> bool:
    """Evaluate a CNF formula where positive int x is x and -x is NOT x."""
    for clause in clauses:
        if not any((assignment[abs(lit)] if lit > 0 else not assignment[abs(lit)]) for lit in clause):
            return False
    return True
Week 17Monte Carlo, Prefix Sum, Heap+Dijkstra Pipeline

Capstone Synthesis & Zanzibar Dispatch Pipeline

Reference Python implementation and self-checks for Z5007 Week 17.

Python Preview
import heapq
import math
import random


def monte_carlo_pi(samples: int, seed: int = 5007) -> float:
    """Estimate pi via randomized dart throwing in [0, 1]^2."""
    rng = random.Random(seed)
    inside = 0
    for _ in range(samples):
Course ProjectBinaryMinHeap O(E log V) vs O(V^2) · Top-K Inverted Index

From-Scratch Project Benchmark Starter (A* Heap & Inverted Index)

Starter benchmark suite aligned with Z5007 Project Guidelines and Grading Rubric (600-node routing + 1,000-item Top-K catalog).

Python Preview
import math
import random
import time


class BinaryMinHeap:
    """From-scratch binary min-heap supporting O(log n) push and pop (no heapq dependency)."""

    def __init__(self) -> None:
        self._data: list[tuple[float, object]] = []