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
- How the bootcamp works
- Syllabus at a glance
- Week 1: Python for DSA and Big-O
- Week 2: Recursion
- Week 3: Searching and Binary Search
- Week 4: Elementary Sorting
- Week 5: Merge Sort, Quick Sort and Linear-Time Sorts
- Week 6: Strings and Pattern Matching
- Week 7: Linked Lists
- Week 8: Stacks and Queues
- Week 9: Hashing
- Week 10: Trees and Binary Search Trees
- Week 11: Heaps and Priority Queues
- Week 12: Graphs, BFS and DFS
- Week 13: Shortest Paths, Topological Sort, Union-Find, MST
- Week 14: Dynamic Programming Foundations
- Week 15: Dynamic Programming on Sequences
- Week 16: Tries, Bit Manipulation and Backtracking
- Complexity reference
- Running the code and tests
- Free resources that pair well with this bootcamp
- Python vs Java vs C++ for DSA
- Common beginner mistakes
- FAQ
- Where to go next
- Contributing
- More free resources
Who this is for
- You know basic Python (variables, loops, functions, lists, dicts) and want to learn DSA properly.
- You are preparing for coding interviews and want the theory behind the patterns.
- You are a student who wants readable reference implementations to check homework against.
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:
- Read the notes in this README (30-60 minutes).
- Read the week’s module in
dsa/. Every function is short and has a docstring that states its complexity. - 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).
- Solve the assignment problems on LeetCode. They are ordered from easier to harder.
- 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:
- A single loop over
nitems: O(n). - Two nested loops over
n: O(n^2). Nested loops where the inner one runsitimes: still O(n^2) because1 + 2 + ... + n = n(n+1)/2. - A loop that halves (or doubles) a value each step: O(log n). This is why binary search and fast power are fast.
- Recursion: count the calls and the work per call. Two calls per level with depth
ngives O(2^n).
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
- Write
fast_power(base, exp)iteratively using the binary digits ofexp. - Write the Sieve of Eratosthenes and explain why the inner loop can start at
i * i. - Time
x in listagainstx in setfor 10^5 items withtimeit.
Assignment
- 1480. Running Sum of 1d Array
- 1672. Richest Customer Wealth
- 412. Fizz Buzz
- 9. Palindrome Number
- 1342. Number of Steps to Reduce a Number to Zero
- 204. Count Primes
Checkpoint
- What is the complexity of checking every pair in a list? Of sorting it first and using two pointers?
- Why is
log2(10^9)only about 30, and why does that matter?
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:
- A base case that returns without recursing.
- A recursive case that makes progress toward the base case.
- 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
- Write
power_setandpermutationswithout looking. Count how many results each returns fornitems. - Write
flattenfor arbitrarily nested lists. - Convert
sum_digitsto a loop. Which version is clearer?
Assignment
- 509. Fibonacci Number
- 344. Reverse String
- 231. Power of Two
- 50. Pow(x, n)
- 21. Merge Two Sorted Lists (solve it recursively)
- 779. K-th Symbol in Grammar
Checkpoint
- What happens if a recursive function has no reachable base case?
- How many calls does memoised
fibonacci(50)make, roughly?
Week 3: Searching and Binary Search
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
- Write
lower_boundandupper_boundwith the half-open template and test them againstbisect. - Write
first_trueand use it to find the smallestkwithk * k * k >= n.
Assignment
- 704. Binary Search
- 35. Search Insert Position
- 69. Sqrt(x)
- 278. First Bad Version
- 374. Guess Number Higher or Lower
- 33. Search in Rotated Sorted Array
- 240. Search a 2D Matrix II
Checkpoint
- Why can
mid = (lo + hi) // 2overflow in Java or C++ but not in Python, and what is the safe form? - What property must a predicate have for binary search on the answer to work?
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 |
- Stable means equal keys keep their original order. It matters when you sort records by one field after sorting by another.
- Insertion sort is fast on nearly sorted data and on tiny arrays, which is why real hybrid sorts use it for small runs. Python’s built-in sort (Timsort, and since Python 3.11 a variant using the Powersort merge policy) exploits existing sorted runs in the data.
- Selection sort makes at most
n - 1swaps, useful only when writes are expensive. - Cyclic sort is a pattern, not a general sort: when values are
1..n, valuevbelongs at indexv - 1. It solves “find the missing / duplicate number” problems in O(n) time and O(1) space.
Build it yourself
- Implement insertion sort and count how many shifts it makes on sorted, reversed and random input.
- Show with a small example of
(key, label)pairs that selection sort is not stable.
Assignment
- 88. Merge Sorted Array
- 977. Squares of a Sorted Array
- 1051. Height Checker
- 268. Missing Number
- 448. Find All Numbers Disappeared in an Array
- 75. Sort Colors
Checkpoint
- Which elementary sort would you use on an almost-sorted array of 50 items, and why?
- What does “stable” mean, with an example where it matters?
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:
- Counting inversions piggybacks on merge: when an element from the right half is placed before remaining left elements, it forms an inversion with each of them.
- Quickselect partitions like quicksort but recurses into only one side, giving the k-th smallest in O(n) expected time.
Build it yourself
- Write merge sort, then modify it to count inversions.
- Write quicksort with the Lomuto partition. Then make it handle many duplicates efficiently (three-way partition).
- Write counting sort and explain why iterating in reverse keeps it stable.
Assignment
- 912. Sort an Array
- 215. Kth Largest Element in an Array
- 179. Largest Number
- 164. Maximum Gap
- 315. Count of Smaller Numbers After Self
- 493. Reverse Pairs
Checkpoint
- Why does a random pivot protect quicksort from sorted input?
- When would you choose counting sort over
sorted()?
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:
- Counting with
collections.Counteror a 26-slot array: anagrams, first unique character. - Two pointers from both ends: palindromes, reversing.
- Expand around centre for palindromic substrings: there are
2n - 1centres (each character and each gap). - Pattern matching. The naive search is O(n·m). Two linear-time alternatives:
- KMP precomputes the prefix function
pi[i]: the length of the longest proper prefix of the pattern that is also a suffix ofpattern[:i+1]. On a mismatch, it jumps back topi[k - 1]instead of restarting, so the text pointer never moves backwards. - Rabin-Karp compares rolling hashes of each window and only compares characters when hashes match. It extends naturally to searching many patterns at once.
- KMP precomputes the prefix function
Example prefix function for "aabaaab": [0, 1, 0, 1, 2, 2, 3].
Build it yourself
- Write the prefix function and KMP search. Test them against
str.findon random strings over a two-letter alphabet (where bugs show up quickly). - Write a rolling hash and verify it against recomputing each window’s hash from scratch.
Assignment
- 14. Longest Common Prefix
- 151. Reverse Words in a String
- 443. String Compression
- 28. Find the Index of the First Occurrence in a String (solve with KMP)
- 459. Repeated Substring Pattern
- 5. Longest Palindromic Substring
Checkpoint
- Why is KMP O(n + m) even though it has a
whileloop inside aforloop? - Why must Rabin-Karp verify a hash match?
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:
- Dummy (sentinel) node before the head so inserting or deleting the first node needs no special case.
DoublyLinkedListuses sentinels at both ends. - Fast and slow pointers: the middle of the list, the n-th node from the end, and cycle detection.
- Floyd’s cycle detection: if fast (2 steps) meets slow (1 step), there is a cycle. Reset one pointer to the head and move both one step at a time; they meet at the cycle’s start.
- Reversal with three pointers (
prev,node,next) is a building block for palindrome checks and k-group reversal.
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
- Implement
SinglyLinkedListwithpush_front,push_back,pop_front,insert,remove,reverse. - Implement
cycle_startand prove (on paper) why the second phase meets at the cycle’s start. - Implement an LRU cache with your
DoublyLinkedListand a dict.
Assignment
- 206. Reverse Linked List
- 876. Middle of the Linked List
- 141. Linked List Cycle
- 142. Linked List Cycle II
- 160. Intersection of Two Linked Lists
- 234. Palindrome Linked List
- 707. Design Linked List
Checkpoint
- Why does a singly linked list need O(n) to remove its last node even with a tail pointer?
- What bug does a dummy head node prevent?
Week 8: Stacks and Queues
Module: dsa/week08_stack_queue.py
Notes
- Stack (LIFO): a Python list with
appendandpop. Used for undo, recursion simulation, bracket matching and expression evaluation. - Queue (FIFO): use
collections.deque(append,popleft). A list’spop(0)is O(n). - Queue from two stacks: push into an in-stack; when the out-stack is empty, move everything over. Each element moves at most once, so operations are amortised O(1).
- Circular queue (ring buffer): a fixed array, a head index and a count; positions wrap with
% capacity. Used in buffers, schedulers and streaming. - Monotonic stack: keep the stack sorted so each element is pushed and popped once. It answers “next greater/smaller element”, “how many days until warmer” and “largest rectangle in a histogram” in O(n).
- Shunting-yard converts infix expressions (
3 + 4 * 2) to postfix (3 4 2 * +) using an operator stack and precedence, and a second stack evaluates the postfix form.
Build it yourself
- Implement
CircularQueueand test the wrap-around case. - Implement
next_greaterand explain why the total work is O(n). - Extend
infix_to_postfixwith the right-associative^operator.
Assignment
- 20. Valid Parentheses
- 232. Implement Queue using Stacks
- 225. Implement Stack using Queues
- 622. Design Circular Queue
- 150. Evaluate Reverse Polish Notation
- 503. Next Greater Element II
- 224. Basic Calculator
Checkpoint
- Why is the two-stack queue amortised O(1) even though one dequeue can move many items?
- What invariant does a monotonic decreasing stack keep?
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:
- Separate chaining: each bucket holds a small list of
(key, value)pairs. The module’sHashMapuses this. - Open addressing: on collision, probe other slots in the same array. CPython’s
dictuses open addressing with a perturbation-based probe sequence.
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:
- Complement lookup: two-sum.
- Frequency counting: anagrams, first unique character, majority element.
- Prefix sum + first-seen index: longest subarray with sum
k, even with negative numbers. - Seen set: duplicates, cycles in sequences.
Build it yourself
- Implement
HashMapwith chaining and resizing; fuzz-test it againstdictwith random operations (see the tests). - Implement a
HashSeton top of yourHashMap.
Assignment
- 706. Design HashMap
- 705. Design HashSet
- 1. Two Sum
- 387. First Unique Character in a String
- 49. Group Anagrams
- 560. Subarray Sum Equals K
- 525. Contiguous Array
Checkpoint
- What is the worst-case lookup time of a hash table, and when does it happen?
- Why must you rehash every key when the table grows?
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
- Implement
BST.insert,containsanddelete(all three delete cases). - Write the four traversals recursively and iteratively.
- Insert 1..1000 in order into your BST and measure its height. Then insert the same values shuffled.
Assignment
- 144. Binary Tree Preorder Traversal
- 94. Binary Tree Inorder Traversal
- 145. Binary Tree Postorder Traversal
- 102. Binary Tree Level Order Traversal
- 701. Insert into a Binary Search Tree
- 450. Delete Node in a BST
- 108. Convert Sorted Array to Binary Search Tree
- 98. Validate Binary Search Tree
Checkpoint
- Which traversal of a BST gives sorted output?
- Why can a BST degrade to O(n), and what fixes it?
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:
- Top-k: a size-k min-heap keeps the k largest in O(n log k).
- k-way merge: merge k sorted lists by repeatedly taking the smallest head.
- Running median: a max-heap for the lower half and a min-heap for the upper half.
- Scheduling: always process the most urgent task next (also the core of Dijkstra in Week 13).
Build it yourself
- Implement
MinHeapwithpush,pop,peekand O(n) heapify. - Implement heap sort with your heap, then make it in-place with a max-heap.
Assignment
- 1046. Last Stone Weight
- 703. Kth Largest Element in a Stream
- 347. Top K Frequent Elements
- 373. Find K Pairs with Smallest Sums
- 23. Merge k Sorted Lists
- 295. Find Median from Data Stream
Checkpoint
- Why does top-k use a min-heap to keep the largest items?
- Where is the second-smallest element of a min-heap guaranteed to be?
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.
- BFS (queue) explores in layers, so the first time it reaches a node is along a shortest path in an unweighted graph. Mark nodes as seen when you enqueue them, not when you dequeue them, or nodes get queued twice.
- DFS (stack or recursion) goes deep first. Use it for connected components, cycle detection, topological order and backtracking.
- Cycle detection: in an undirected graph, a seen neighbour other than the parent means a cycle. In a directed graph, use three colours; reaching a grey node (still on the current path) means a back edge, which is a cycle.
- Bipartite check: 2-colour with BFS; an edge between equal colours fails.
Both BFS and DFS run in O(V + E).
Build it yourself
- Implement
Graph,bfs_orderandshortest_path_unweightedwith parent pointers. - Implement directed cycle detection with colours, iteratively.
- Solve “number of islands” with both BFS and DFS.
Assignment
- 1971. Find if Path Exists in Graph
- 733. Flood Fill
- 200. Number of Islands
- 547. Number of Provinces
- 841. Keys and Rooms
- 785. Is Graph Bipartite?
- 1091. Shortest Path in Binary Matrix
Checkpoint
- Why does BFS find shortest paths only in unweighted graphs?
- Why is the undirected cycle check wrong for directed graphs?
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 |
- Dijkstra pops the closest unfinished node from a heap; once popped, its distance is final. Stale heap entries are skipped instead of decreased.
- Bellman-Ford relaxes every edge
V - 1times. If an edge can still be relaxed after that, a negative cycle is reachable. - Kahn’s algorithm repeatedly removes nodes with indegree 0. If some nodes are never removed, the graph has a cycle.
- Union-find with path compression and union by size makes
findeffectively constant time (the inverse Ackermann function). - Kruskal sorts edges and adds each one that joins two different components (checked with union-find). Prim grows one tree from a start node with a heap of crossing edges.
Build it yourself
- Implement Dijkstra with a heap and lazy deletion.
- Implement union-find with both optimisations and count components while adding edges.
- Implement Kruskal on top of your union-find.
Assignment
- 743. Network Delay Time
- 1631. Path With Minimum Effort
- 787. Cheapest Flights Within K Stops
- 207. Course Schedule
- 210. Course Schedule II
- 684. Redundant Connection
- 1584. Min Cost to Connect All Points
Checkpoint
- Give a three-node example where Dijkstra fails with a negative edge.
- Why does Kruskal’s algorithm need to know whether two nodes are already connected?
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:
- State: what does
dp[i](ordp[i][j]) mean, in one sentence? Example: “best[a]is the fewest coins that make amounta.” - Transition: how does a state depend on smaller ones?
best[a] = 1 + min(best[a - c] for c in coins). - Base case:
best[0] = 0. - 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:
- Counting paths: climbing stairs, grid paths.
- Unbounded knapsack: coin change (min coins, number of combinations), rod cutting.
- 0/1 knapsack: each item once; iterate capacity downwards in the 1-D version so an item is not reused.
- Take or skip: house robber.
- Kadane’s algorithm: maximum subarray as a one-variable DP.
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
- Solve coin change top-down with memoisation, then bottom-up, then compare.
- Write 0/1 knapsack with a 2-D table, then reduce it to one row. Check it against brute force (see the tests).
Assignment
- 70. Climbing Stairs
- 198. House Robber
- 53. Maximum Subarray
- 64. Minimum Path Sum
- 63. Unique Paths II
- 322. Coin Change
- 518. Coin Change II
- 416. Partition Equal Subset Sum
Checkpoint
- State, transition, base case and order for coin change, from memory.
- Why does the 1-D 0/1 knapsack loop over capacity backwards?
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
- Write LCS bottom-up and reconstruct one subsequence.
- Write LIS in O(n^2) with reconstruction, then the O(n log n) length-only version.
- Write edit distance and print the actual edit operations.
Assignment
- 1143. Longest Common Subsequence
- 72. Edit Distance
- 300. Longest Increasing Subsequence
- 516. Longest Palindromic Subsequence
- 139. Word Break
- 115. Distinct Subsequences
Checkpoint
- Why does the
tailsarray in patience sorting not hold an actual increasing subsequence? - In what order must an interval DP table be filled?
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
- Implement a trie with
insert,contains,starts_withandwords_with_prefix. - Solve N-Queens with sets first, then with bitmasks, and compare speed for
n = 10. - Write a Sudoku solver and add the “fewest candidates first” heuristic.
Assignment
- 208. Implement Trie (Prefix Tree)
- 191. Number of 1 Bits
- 136. Single Number
- 78. Subsets
- 39. Combination Sum
- 52. N-Queens II
- 37. Sudoku Solver
Checkpoint
- Why is trie lookup independent of the number of stored words?
- What is the difference between backtracking and plain brute force?
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 documentation:
collections,heapqandbisect - Python wiki: TimeComplexity, the costs of built-in operations
- VisuAlgo, animations of sorting, heaps, BSTs and graph algorithms
- MIT OpenCourseWare 6.006 Introduction to Algorithms, free lectures and problem sets
- Open Data Structures, a free textbook with Python-like pseudocode
- CP-Algorithms, detailed articles on graph, string and number theory algorithms
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
- More interview practice: an ordered problem list with key insights, such as LeetCode’s Top Interview 150 or Grind 75.
- Deeper algorithms: Algorithms, 4th Edition booksite and the companion Coursera course, Part I (free to audit at the time of review).
- Competitive programming: the USACO Guide and the CSES Problem Set take you from these foundations to contest-level problems.
- Quick reference: Big-O Cheat Sheet and Programiz DSA tutorials for a second explanation of any topic.
Contributing
PRs are welcome. Keep entries accurate:
- New code goes in the matching week’s module, uses only the standard library, and comes with tests.
- Run
python3 -m unittest discover -s tests -t .before opening a PR. - Assignment links must point to real, free LeetCode problems that match the week’s topic.
- Notes should stay short and correct; open an issue if you spot an error.
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.