Skip to the content.

DSA Bootcamp in Python: Data Structures and Algorithms, Week by Week

A complete, free data structures and algorithms (DSA) bootcamp in Python. Over 16 weeks you go from Big-O and recursion to graphs, dynamic programming, tries and backtracking. Every week has short notes, a tested Python module you can read and run, build-it-yourself exercises, and a LeetCode assignment list. It is for beginners and self-taught developers who want a structured path through DSA for coding interviews or a CS course, using Python instead of Java or C++.

Last reviewed: December 2026

Table of Contents

Who this is for

You do not need a CS degree or advanced math. Week 1 covers the math you need (logarithms, sums, Big-O).

How the bootcamp works

Each week takes roughly 6-10 hours:

  1. Read the notes in this README (30-60 minutes).
  2. Read the week’s module in dsa/. Every function is short and has a docstring that states its complexity.
  3. Do the build-it-yourself exercises. Close the module and re-implement the core structure from memory. Then run the tests against your version (swap the import).
  4. Solve the assignment problems on LeetCode. They are ordered from easier to harder.
  5. Pass the checkpoint: answer the questions out loud without notes. If you cannot, repeat the week’s exercises before moving on.

Missing a week is fine. Skipping the build-it-yourself step is not; writing structures from scratch is what makes them stick.

Syllabus at a glance

Week Topic Module Key ideas
1 Python for DSA, Big-O week01_complexity.py Counting operations, O(n) vs O(n^2), fast power, sieve
2 Recursion week02_recursion.py Base case, call stack, memoisation, Tower of Hanoi
3 Searching week03_searching.py Binary search templates, lower/upper bound, search on the answer
4 Elementary sorts week04_sorting_basic.py Bubble, selection, insertion, cyclic sort, stability
5 Advanced sorts week05_sorting_advanced.py Merge sort, quicksort, quickselect, counting and radix sort
6 Strings week06_strings.py Immutability, KMP, Rabin-Karp, expand around centre
7 Linked lists week07_linked_list.py Pointers, sentinels, fast/slow pointers, Floyd’s cycle detection
8 Stacks and queues week08_stack_queue.py LIFO/FIFO, ring buffer, monotonic stack, shunting-yard
9 Hashing week09_hashing.py Hash functions, chaining, load factor, resizing
10 Trees and BSTs week10_trees.py Traversals, BST insert/delete, balance
11 Heaps week11_heaps.py Array-backed heap, heapify in O(n), top-k, k-way merge
12 Graphs I week12_graphs.py Adjacency lists, BFS, DFS, components, cycles, bipartite
13 Graphs II week13_graph_algorithms.py Dijkstra, Bellman-Ford, Kahn’s algorithm, union-find, Kruskal, Prim
14 DP I week14_dp_basics.py States and transitions, knapsack, coin change, grid DP
15 DP II week15_dp_sequences.py LCS, edit distance, LIS, interval DP
16 Tries, bits, backtracking week16_tries_bits_backtracking.py Prefix trees, bit tricks, N-Queens, Sudoku

Week 1: Python for DSA and Big-O

Module: dsa/week01_complexity.py

Notes

Big-O describes how the running time (or memory) grows as the input size n grows, ignoring constant factors and smaller terms. 3n^2 + 10n + 7 is O(n^2).

How to read code for complexity:

Python costs that surprise beginners:

Operation Cost
x in some_list O(n)
x in some_set, some_dict[key] O(1) on average
lst.pop() / lst.append(x) O(1) amortised
lst.pop(0) / lst.insert(0, x) O(n), use collections.deque
lst[a:b] (slicing) O(b - a), it copies
s1 + s2 in a loop O(n^2) total, use "".join(parts)
sorted(lst) O(n log n)

Read the two count_pairs_with_sum_* functions side by side: the dictionary turns an O(n^2) algorithm into O(n) by remembering what you have already seen. That trade of memory for time is the most common optimisation in this whole bootcamp.

Build it yourself

  1. Write fast_power(base, exp) iteratively using the binary digits of exp.
  2. Write the Sieve of Eratosthenes and explain why the inner loop can start at i * i.
  3. Time x in list against x in set for 10^5 items with timeit.

Assignment

Checkpoint


Week 2: Recursion

Module: dsa/week02_recursion.py

Notes

A recursive function solves a problem by calling itself on a smaller version of the same problem. Every correct recursive function has:

  1. A base case that returns without recursing.
  2. A recursive case that makes progress toward the base case.
  3. Trust: assume the smaller call returns the right answer, and only think about how to combine it.

The call stack stores one frame per active call. Python’s default recursion limit is about 1000 frames (sys.getrecursionlimit()), so deep recursion on large inputs should be rewritten with an explicit stack or loop.

Draw the recursion tree to find the complexity. Naive Fibonacci branches twice per call, so it makes O(2^n) calls; with functools.lru_cache each value is computed once and it becomes O(n). That is the bridge to dynamic programming in Week 14.

The Tower of Hanoi shows the “trust” idea best: to move n discs, move n - 1 to the spare peg, move the largest, then move n - 1 on top. That gives T(n) = 2T(n - 1) + 1 = 2^n - 1 moves.

Build it yourself

  1. Write power_set and permutations without looking. Count how many results each returns for n items.
  2. Write flatten for arbitrarily nested lists.
  3. Convert sum_digits to a loop. Which version is clearer?

Assignment

Checkpoint


Module: dsa/week03_searching.py

Notes

Binary search works on anything monotonic: a sorted array, or a yes/no question whose answer flips once from “no” to “yes” as the input grows. Each step halves the search space, so it takes O(log n) steps.

Most binary search bugs are off-by-one errors. Pick one template and use it everywhere:

Template Loop Use when
Closed [lo, hi] while lo <= hi, hi = mid - 1 Looking for an exact value
Half-open [lo, hi) while lo < hi, hi = mid Looking for a boundary (lower/upper bound)
first_true(lo, hi, predicate) Store the candidate, keep searching left “Smallest x that works” questions

lower_bound is the first index with value >= target; upper_bound is the first index with value > target. The number of copies of target is their difference. Python’s bisect.bisect_left and bisect.bisect_right are exactly these two.

Binary search on the answer is the pattern behind problems like “minimum speed to finish in time” or “minimum capacity to ship in D days”: you search over possible answers and test each with a greedy check. integer_sqrt in the module shows the pattern with the predicate x * x > n.

Two other searches worth knowing: a rotated sorted array (one half around mid is always sorted) and a row-and-column sorted matrix (start at the top-right corner; each comparison removes a row or a column).

Build it yourself

  1. Write lower_bound and upper_bound with the half-open template and test them against bisect.
  2. Write first_true and use it to find the smallest k with k * k * k >= n.

Assignment

Checkpoint


Week 4: Elementary Sorting

Module: dsa/week04_sorting_basic.py

Notes

Algorithm Best Average Worst Extra space Stable
Bubble sort (early exit) O(n) O(n^2) O(n^2) O(1) Yes
Selection sort O(n^2) O(n^2) O(n^2) O(1) No
Insertion sort O(n) O(n^2) O(n^2) O(1) Yes
Cyclic sort (values 1..n) O(n) O(n) O(n) O(1) n/a

Build it yourself

  1. Implement insertion sort and count how many shifts it makes on sorted, reversed and random input.
  2. Show with a small example of (key, label) pairs that selection sort is not stable.

Assignment

Checkpoint


Week 5: Merge Sort, Quick Sort and Linear-Time Sorts

Module: dsa/week05_sorting_advanced.py

Notes

Divide and conquer: split the problem, solve the parts recursively, combine. The recurrence T(n) = 2T(n/2) + O(n) solves to O(n log n): there are log n levels and each level does O(n) work in total.

Algorithm Average Worst Extra space Stable Notes
Merge sort O(n log n) O(n log n) O(n) Yes Predictable; good for linked lists and external sorting
Quick sort (random pivot) O(n log n) O(n^2) O(log n) stack No Fast in practice; random pivot makes the worst case unlikely
Heap sort (Week 11) O(n log n) O(n log n) O(1) No In place, guaranteed bound
Counting sort O(n + k) O(n + k) O(n + k) Yes k = value range
Radix sort (LSD) O(d (n + b)) O(d (n + b)) O(n + b) Yes d digits in base b

Comparison sorts cannot beat O(n log n) in the worst case: there are n! possible orders, and each comparison gives one bit of information, so you need about log2(n!) ≈ n log2 n comparisons. Counting and radix sort avoid the bound by not comparing elements.

Two tools that reuse these ideas:

Build it yourself

  1. Write merge sort, then modify it to count inversions.
  2. Write quicksort with the Lomuto partition. Then make it handle many duplicates efficiently (three-way partition).
  3. Write counting sort and explain why iterating in reverse keeps it stable.

Assignment

Checkpoint


Week 6: Strings and Pattern Matching

Module: dsa/week06_strings.py

Notes

Python strings are immutable: every s += ch may build a new string. Collect pieces in a list and "".join them once (see compress).

Core string techniques:

Example prefix function for "aabaaab": [0, 1, 0, 1, 2, 2, 3].

Build it yourself

  1. Write the prefix function and KMP search. Test them against str.find on random strings over a two-letter alphabet (where bugs show up quickly).
  2. Write a rolling hash and verify it against recomputing each window’s hash from scratch.

Assignment

Checkpoint


Week 7: Linked Lists

Module: dsa/week07_linked_list.py

Notes

A linked list stores each value in a node that points to the next node. Compared with a Python list (a dynamic array):

Operation Dynamic array Singly linked list (head + tail) Doubly linked list
Access by index O(1) O(n) O(n)
Insert/remove at front O(n) O(1) O(1)
Append at back O(1) amortised O(1) O(1)
Remove at back O(1) O(n) O(1)
Remove a known node O(n) O(n) (need the previous node) O(1)

Techniques that solve most linked list problems:

Doubly linked lists plus a hash map give an LRU cache with O(1) operations; Python’s collections.OrderedDict is built on that idea.

Build it yourself

  1. Implement SinglyLinkedList with push_front, push_back, pop_front, insert, remove, reverse.
  2. Implement cycle_start and prove (on paper) why the second phase meets at the cycle’s start.
  3. Implement an LRU cache with your DoublyLinkedList and a dict.

Assignment

Checkpoint


Week 8: Stacks and Queues

Module: dsa/week08_stack_queue.py

Notes

Build it yourself

  1. Implement CircularQueue and test the wrap-around case.
  2. Implement next_greater and explain why the total work is O(n).
  3. Extend infix_to_postfix with the right-associative ^ operator.

Assignment

Checkpoint


Week 9: Hashing

Module: dsa/week09_hashing.py

Notes

A hash table maps a key to a bucket with hash(key) % capacity. Two keys landing in the same bucket is a collision. Two standard ways to handle it:

The load factor is items / buckets. Keep it bounded (this module resizes at 0.75) and lookups stay O(1) on average. Resizing is O(n) but happens rarely enough to be amortised O(1) per insert.

Rules for keys: equal keys must have equal hashes, and keys must not change while stored. That is why Python lists cannot be dict keys but tuples can.

Patterns built on hashing:

Build it yourself

  1. Implement HashMap with chaining and resizing; fuzz-test it against dict with random operations (see the tests).
  2. Implement a HashSet on top of your HashMap.

Assignment

Checkpoint


Week 10: Trees and Binary Search Trees

Module: dsa/week10_trees.py

Notes

Vocabulary: root, parent, child, leaf, depth (distance from the root), height (longest path down), subtree.

Traversals (for the tree 4 → (2 → 1, 3), (6 → 5, 7)):

Traversal Order Result Typical use
Preorder node, left, right 4 2 1 3 6 5 7 Copying or serialising a tree
Inorder left, node, right 1 2 3 4 5 6 7 Sorted output from a BST
Postorder left, right, node 1 3 2 5 7 6 4 Deleting a tree, computing heights
Level order (BFS) level by level [4] [2 6] [1 3 5 7] Shortest depth, right-side view

The module writes all four iteratively; recursive versions are three lines each and worth writing too.

A binary search tree keeps everything in the left subtree smaller and everything in the right subtree larger, at every node. Search, insert and delete take O(h), where h is the height: O(log n) for a balanced tree, O(n) when you insert sorted data into a plain BST. Self-balancing trees (AVL, red-black) keep h in O(log n); sorted_array_to_bst shows the balanced shape they aim for.

Deleting a node with two children: replace its value with its in-order successor (the smallest value in the right subtree), then delete the successor, which has at most one child.

Validating a BST needs a (low, high) range passed down the tree; comparing a node only with its children misses violations deeper down.

Build it yourself

  1. Implement BST.insert, contains and delete (all three delete cases).
  2. Write the four traversals recursively and iteratively.
  3. Insert 1..1000 in order into your BST and measure its height. Then insert the same values shuffled.

Assignment

Checkpoint


Week 11: Heaps and Priority Queues

Module: dsa/week11_heaps.py

Notes

A binary min-heap is a complete binary tree stored in an array where every parent is <= its children. For index i: children at 2i + 1 and 2i + 2, parent at (i - 1) // 2.

Operation Cost How
peek min O(1) a[0]
push O(log n) Append, then sift up
pop min O(log n) Move the last item to the root, then sift down
build from n items O(n) Sift down from the last parent to the root

Building a heap bottom-up is O(n), not O(n log n), because most nodes are near the bottom and sift down only a short distance.

Python’s heapq is a min-heap over a plain list. For a max-heap, push negated numbers. For records, push tuples like (priority, counter, item); the counter breaks ties so items never need to be compared.

Heap patterns:

Build it yourself

  1. Implement MinHeap with push, pop, peek and O(n) heapify.
  2. Implement heap sort with your heap, then make it in-place with a max-heap.

Assignment

Checkpoint


Week 12: Graphs, BFS and DFS

Module: dsa/week12_graphs.py

Notes

A graph is a set of nodes (vertices) and edges. Edges may be directed or undirected, weighted or unweighted.

Representation Space Check edge (u, v) List neighbours Best for
Adjacency list O(V + E) O(degree) O(degree) Sparse graphs (most real ones)
Adjacency matrix O(V^2) O(1) O(V) Dense graphs, small V
Edge list O(E) O(E) O(E) Kruskal’s algorithm

A grid is a graph too: each cell is a node and its 4 (or 8) neighbours are edges. You rarely build it explicitly.

Both BFS and DFS run in O(V + E).

Build it yourself

  1. Implement Graph, bfs_order and shortest_path_unweighted with parent pointers.
  2. Implement directed cycle detection with colours, iteratively.
  3. Solve “number of islands” with both BFS and DFS.

Assignment

Checkpoint


Week 13: Shortest Paths, Topological Sort, Union-Find, MST

Module: dsa/week13_graph_algorithms.py

Notes

Problem Algorithm Complexity Condition
Shortest paths, unweighted BFS O(V + E) All edges cost 1
Shortest paths, weights >= 0 Dijkstra (binary heap) O((V + E) log V) No negative edges
Shortest paths, negative weights Bellman-Ford O(V · E) Detects negative cycles
All-pairs shortest paths Floyd-Warshall O(V^3) Small V
Ordering with dependencies Topological sort (Kahn) O(V + E) Must be a DAG
Dynamic connectivity Union-find Nearly O(1) per op Only merges, no splits
Minimum spanning tree Kruskal or Prim O(E log E) / O(E log V) Connected, undirected

Build it yourself

  1. Implement Dijkstra with a heap and lazy deletion.
  2. Implement union-find with both optimisations and count components while adding edges.
  3. Implement Kruskal on top of your union-find.

Assignment

Checkpoint


Week 14: Dynamic Programming Foundations

Module: dsa/week14_dp_basics.py

Notes

Dynamic programming (DP) applies when a problem has overlapping subproblems (the same smaller question is asked many times) and optimal substructure (the best answer is built from best answers to smaller questions).

A four-step recipe:

  1. State: what does dp[i] (or dp[i][j]) mean, in one sentence? Example: “best[a] is the fewest coins that make amount a.”
  2. Transition: how does a state depend on smaller ones? best[a] = 1 + min(best[a - c] for c in coins).
  3. Base case: best[0] = 0.
  4. Order: compute states so dependencies are ready first (increasing a).

Top-down (recursion + lru_cache) and bottom-up (a loop filling a table) give the same answers; bottom-up avoids recursion limits and often allows space optimisation to one row or a few variables.

Classic families covered this week:

Combinations vs permutations in coin counting: put coins in the outer loop to count each multiset once; put amounts in the outer loop to count every order.

Build it yourself

  1. Solve coin change top-down with memoisation, then bottom-up, then compare.
  2. Write 0/1 knapsack with a 2-D table, then reduce it to one row. Check it against brute force (see the tests).

Assignment

Checkpoint


Week 15: Dynamic Programming on Sequences

Module: dsa/week15_dp_sequences.py

Notes

Two-sequence DP uses dp[i][j] for “the answer for the first i characters of a and the first j of b” (or suffixes, as in the module’s lcs).

Problem Transition Complexity
Longest common subsequence Match: 1 + dp[i+1][j+1]; else max(dp[i+1][j], dp[i][j+1]) O(n·m)
Edit distance Match: diagonal; else 1 + min(insert, delete, replace) O(n·m)
Longest increasing subsequence O(n^2) DP, or O(n log n) patience sorting with bisect O(n log n)
Longest palindromic subsequence LCS of the string and its reverse O(n^2)
Word break ok[i] = any(ok[j] and s[j:i] in words) O(n^2) checks
Matrix chain multiplication Interval DP: try every split point k O(n^3)

Reconstructing the answer: keep the full table (or parent pointers) and walk back from the final state, as lcs and lis_sequence do. Space-optimised versions give only the length.

Interval DP solves problems on ranges [i, j] by trying every split point and combining the two sides. Fill it by increasing interval length so shorter intervals are ready first.

Build it yourself

  1. Write LCS bottom-up and reconstruct one subsequence.
  2. Write LIS in O(n^2) with reconstruction, then the O(n log n) length-only version.
  3. Write edit distance and print the actual edit operations.

Assignment

Checkpoint


Week 16: Tries, Bit Manipulation and Backtracking

Module: dsa/week16_tries_bits_backtracking.py

Notes

Tries (prefix trees) store strings character by character, so all words with a common prefix share a path. Insert and lookup take O(L) for a word of length L, independent of how many words are stored. Uses: autocomplete, spell check, word search on a board.

Bit manipulation tricks:

Expression Meaning
x & 1 Is x odd?
x >> i & 1 Is bit i set?
x \| (1 << i) Set bit i
x & ~(1 << i) Clear bit i
x & (x - 1) Clear the lowest set bit
x & -x Isolate the lowest set bit
a ^ a == 0 XOR cancels pairs (single number)
n > 0 and n & (n - 1) == 0 n is a power of two

A bitmask of n bits can represent a subset of n items, so range(1 << n) enumerates all subsets.

Backtracking builds a solution step by step and undoes a choice when it cannot lead to a valid answer:

def backtrack(state):
    if is_complete(state):
        record(state)
        return
    for choice in choices(state):
        if is_valid(state, choice):
            apply(state, choice)
            backtrack(state)
            undo(state, choice)

Pruning (stopping early when a partial state is invalid) is what makes backtracking practical. N-Queens with bitmasks and the Sudoku solver both prune using sets of used columns, diagonals, rows and boxes.

Build it yourself

  1. Implement a trie with insert, contains, starts_with and words_with_prefix.
  2. Solve N-Queens with sets first, then with bitmasks, and compare speed for n = 10.
  3. Write a Sudoku solver and add the “fewest candidates first” heuristic.

Assignment

Checkpoint


Complexity reference

Data structure Access Search Insert Delete Notes
Dynamic array (list) O(1) O(n) O(1) amortised at end, O(n) elsewhere O(1) at end, O(n) elsewhere Cache friendly
Singly linked list O(n) O(n) O(1) at head O(1) at head  
Stack / queue (deque) O(1) at ends O(n) O(1) O(1)  
Hash table (dict, set) n/a O(1) average O(1) average O(1) average O(n) worst case
Binary search tree (balanced) O(log n) O(log n) O(log n) O(log n) Plain BST: O(n) worst
Binary heap O(1) min O(n) O(log n) O(log n) pop min  
Trie n/a O(L) O(L) O(L) L = key length
Union-find n/a ~O(1) find ~O(1) union n/a With both optimisations
Algorithm Time Space
Binary search O(log n) O(1)
Merge sort O(n log n) O(n)
Quicksort O(n log n) average, O(n^2) worst O(log n)
BFS / DFS O(V + E) O(V)
Dijkstra (binary heap) O((V + E) log V) O(V)
Bellman-Ford O(V · E) O(V)
Topological sort O(V + E) O(V)
Kruskal O(E log E) O(V)
KMP O(n + m) O(m)

Running the code and tests

Requirements: Python 3.10 or newer (the code uses X | None type hints). No third-party packages.

git clone https://github.com/Ralpberry-Labs/dsa-bootcamp-python.git
cd dsa-bootcamp-python
python3 -m unittest discover -s tests -t .

Use a module in a REPL:

>>> from dsa.week13_graph_algorithms import dijkstra
>>> dijkstra([("A", "B", 4), ("A", "C", 1), ("C", "B", 2)], "A")
{'A': 0, 'C': 1, 'B': 3}
>>> from dsa.week16_tries_bits_backtracking import n_queens_count
>>> n_queens_count(8)
92

To test your own implementation, copy a week’s module, replace the function bodies with your code, and point the matching test file at your module.

Layout:

dsa/
  week01_complexity.py ... week16_tries_bits_backtracking.py
tests/
  test_weeks_01_08.py
  test_weeks_09_16.py

Free resources that pair well with this bootcamp

Python vs Java vs C++ for DSA

  Python Java C++
Lines of code per solution Fewest Most Medium
Built-in heap heapq (min-heap) PriorityQueue std::priority_queue (max-heap)
Built-in balanced BST / sorted map None in the standard library TreeMap, TreeSet std::map, std::set
Integer overflow Never (arbitrary precision) Silent wrap-around Undefined behaviour for signed ints
Speed Slowest; fine for interviews, tight for some contests Fast Fastest
Best for Interviews, learning, readability Interviews, Android/backend roles Competitive programming

If you need a sorted container in Python, the third-party sortedcontainers package is popular, but interviews and this bootcamp avoid it: use bisect on a list or a heap instead.

Common beginner mistakes

Mistake Example Fix
Shared inner lists [[0] * m] * n [[0] * m for _ in range(n)]
Mutable default argument def f(path=[]) def f(path=None) then path = path or []
Appending a list that you later change result.append(path) in backtracking result.append(path[:])
Queue with list.pop(0) BFS on large graphs is O(n^2) collections.deque and popleft()
Recursion too deep DFS on a 10^5-node path Iterative stack, or sys.setrecursionlimit with care
Modifying a list while iterating for x in a: a.remove(x) Build a new list
Forgetting the visited set Graph BFS loops forever on cycles Mark nodes when you enqueue them
Off-by-one in binary search while lo < hi with hi = mid - 1 Use one template consistently (Week 3)

FAQ

How long does the bootcamp take? Sixteen weeks at 6-10 hours a week. With more time per week you can finish in 8-10 weeks; do not skip the build-it-yourself exercises to go faster.

Is Python good enough for coding interviews? Yes. It is accepted at nearly every company that runs coding interviews, and its short syntax leaves more time for thinking. Know its costs (Week 1 table) so you can discuss complexity accurately.

Do I need to know math? Only basics: exponents, logarithms, sums like 1 + 2 + ... + n, and modular arithmetic for some problems. Week 1 introduces what you need.

How many LeetCode problems should I solve? The assignments here total about 110. Solving those well, then 50-100 more mixed problems, prepares most people for typical interviews. Understanding matters more than the count.

What should I do when I am stuck for more than 40 minutes? Read a hint or the notes for the pattern, then try again. If you read a full solution, re-solve the problem from scratch the next day and again a week later.

Can I use this for a university course? Yes. The modules are small reference implementations with tests. Check your course’s rules on collaboration before submitting anything based on them.

Where to go next

Contributing

PRs are welcome. Keep entries accurate:

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.