Graphs: traversal, shortest paths and union–find
CS · Chapter 412 min readAsked at Hudson River Trading, Jump, Citadel Securities, Optiver
Assumes Trees and heaps: BSTs, priority queues and range queries.
After this lesson you should be able to
- Choose between BFS and DFS from the question.
- Pick the right shortest-path algorithm for the edge weights.
- Recognise the problems union–find solves.
Graph questions are usually easy once the graph is identified, and identifying it is the difficulty: currencies and exchange rates, instruments and dependencies, states and transitions. The algorithms themselves are a short list chosen by two properties — are the edges weighted, and can the weights be negative.
| Aspect | BFS | DFS |
|---|---|---|
| Explores | Level by level | As deep as possible first |
| Uses | A queue | A stack, or recursion |
| Finds | Shortest path in an unweighted graph | Any path; cycles; topological order |
| Memory | The whole frontier — can be wide | The current depth |
| Good for | Minimum hops, level structure | Connectivity, ordering, backtracking |
| Algorithm | Handles | Complexity |
|---|---|---|
| BFS | Unweighted | |
| Dijkstra | Non-negative weights | with a heap |
| Bellman–Ford | Negative weights; detects negative cycles | |
| Floyd–Warshall | All pairs | |
| A* | Single target, with a heuristic | Depends on the heuristic |
Why Dijkstra breaks on negative edges. Dijkstra finalises a node as soon as it is the closest unvisited one, on the reasoning that no later path could be shorter — every remaining edge only adds distance. A negative edge destroys that reasoning: a longer detour can come back cheaper, so a node finalised early may be wrong and nothing ever revisits it. Bellman–Ford makes no such commitment and simply relaxes every edge times, which is slower and correct. If a further relaxation still improves something, there is a negative cycle.
The rest of this lesson is in Premium
You have read the opening. 11 more sections follow, including 4 worked examples and 3 quick checks.
Nothing is charged for 7 days, and you can cancel before then. Or read Complexity: reading it off, and deriving it in full, free.