Overview
Curated: · Written: · Reviewed:
Graphs
In one line
A graph is a set of vertices joined by edges, where cycles, multiple parents and disconnected pieces are all allowed. Reach for it whenever the problem is about connections or transitions between states, then choose BFS, Dijkstra, Bellman-Ford or DFS/union-find by whether the question is about distance or structure and whether the weights are negative.
Key definitions
- Vertex (state): what one node means in the problem. For a state-space graph it is position plus whatever the transitions depend on, such as keys held.
- Edge (transition): a single legal move between two vertices.
- Back edge: a directed edge to a vertex still on the recursion stack; its presence is a cycle.
- Stale heap entry: an old, larger distance left in the Dijkstra priority queue after a shorter one was pushed.
- Frontier: the set of vertices queued but not yet expanded; it often dominates memory.
- Multi-source search: a traversal seeded with every source at distance zero.
Formulas and complexity
Always give the bound in both V and E. A dense graph makes E close to V^2, so O(V + E) is effectively quadratic.
How it works
BFS expands vertices in order of edge-count distance, so the first arrival at a vertex is a fewest-edge path. Mark a vertex when it is enqueued, not when it is dequeued, or it enters the queue once per incoming edge. Dijkstra finalises the smallest tentative distance on each extraction and pushes improvements as new heap entries, skipping stale ones. Non-negative weights are what make that finalisation safe.
When to use and when not to
| Situation | Use | Avoid |
|---|---|---|
| Unweighted shortest path | BFS | Dijkstra (same answer, extra log factor) |
| Non-negative weights | Dijkstra | BFS on weights |
| Negative edges, no negative cycle reachable | Bellman-Ford | Dijkstra (silently wrong) |
| Weights only 0 or 1 | 0-1 BFS | Heap (slower by a log factor) |
| Cycle or topological order | DFS (3-colour) or Kahn | Single visited set |
| Incremental connectivity, MST | Union-find | Rerunning BFS per edge |
| Many sources, nearest distance | Multi-source BFS | One BFS per source |
| Dense graph, edge queries | Adjacency matrix | Adjacency list |
Traps interviewers probe
- Marking visited at dequeue. The answer stays correct, but the queue can hold up to E entries. Fix: mark on enqueue and assert each vertex enters once.
- Single visited set for directed cycles. A diamond A→B, A→C, B→D, C→D reports a false cycle at D. Fix: keep a separate in-progress (grey) set and report only back edges to grey vertices.
- Dijkstra with a negative edge. It finalises a vertex and never revisits it, so it returns a wrong distance with no error. Fix: check the weight domain, and use Bellman-Ford when negative edges exist.
- Position as the vertex in a stateful search. Marking a cell seen under one key set blocks reaching it with a better set. Fix: key visited on (cell, keys).
- Undirected cycle check by parent vertex. Parallel edges form a genuine two-cycle that the parent check misses. Fix: exclude by edge identity.
Interview tips
Opening. Say what a vertex is, then name the weight and sign assumptions that select the algorithm.
Expect these follow-ups:
- What changes if the weights are negative? Bellman-Ford, with a negative-cycle check.
- What if the graph is huge? Address the frontier and visited-set memory, and consider iterative deepening.
- How do you get the path, not only the length? Store predecessors during the search.
- Is the topological order unique? Only if the DAG has a Hamiltonian path; assert the ordering property in tests.
30-second answer outline:
- Model: vertex = state, edge = legal move.
- Weights: unweighted, 0/1, non-negative or negative.
- Pick the algorithm and state its bound, for example O((V + E) log V).
- Name the trap you avoid, such as marking on enqueue or checking the negative-weight domain.
- Name the evidence: a test on a diamond or path graph, and a comparison against a reference search on small random graphs.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.