Graphs Advanced
Lesson, slides, and applied problem sets.
View SlidesLesson
Graphs Advanced
Why this module exists
You already know DFS/BFS for traversal. Advanced graph interviews usually pivot to ordering and optimal paths. This module focuses on:
- Topological sorting — ordering tasks with prerequisites
- Cycle detection — proving an ordering is impossible
- Shortest paths with weights — Dijkstra’s greedy frontier
Mastering these gives you a toolkit for scheduling, dependency management, and network routing problems.
1) Topological Sort (Kahn’s Algorithm)
If edges mean “must come before,” then a valid order is a topological ordering.
Kahn’s algorithm (BFS on in-degrees):
- Count in-degrees for every node.
- Push all nodes with in-degree 0 into a queue.
- Pop, append to order, and reduce neighbors’ in-degree.
- If you processed all nodes, you have an ordering.
Invariant: Nodes in the queue have no remaining prerequisites.
Cycle detection: If you can’t process all nodes, a cycle exists.
2) Course Schedule vs Course Order
- Course Schedule asks: “Does an order exist?”
- Course Order asks: “Return any valid order.”
Same algorithm, different output:
- Schedule returns
visited == n. - Order returns the list if
len(order) == n, otherwise[].
3) Dijkstra’s Algorithm (Shortest Paths)
When edges have positive weights, greedy works:
- Start from the source.
- Always expand the closest unvisited node.
- Relax edges to improve distances.
Key idea: once a node is popped from the min-heap, its distance is final.
Common traps:
- Negative weights break the greedy property.
- Use a min-heap and ignore stale entries.
Interview signals
- You can model real systems (dependencies, pipelines, build graphs).
- You can reason about constraints (cycles make an order impossible).
- You can justify greedy correctness (Dijkstra).
Problems in this module
- Course Schedule — detect cycles in prerequisites
- Course Order — produce a valid topological ordering
- Dijkstra Shortest Path — shortest distances in weighted graphs
Module Items
Course Schedule
Detect if all courses can be completed by checking for cycles.
Course Order
Return any valid topological ordering or an empty list if impossible.
Dijkstra Shortest Path
Compute shortest distances from a source in a weighted graph.
Graphs Advanced Checkpoint
Topological sorting and shortest paths.