CS concepts
Graph Algorithms Explained: 5 Moves for Coding Interviews
Updated Nov 27, 2026 · 5 min read
Most interview graph questions come down to five moves. Use BFS for the fewest steps when every step costs the same, DFS to count groups or fill regions, topological sort when things depend on other things, Dijkstra for the cheapest path with costs, and union-find when links arrive one at a time and you keep asking if two things are connected.
Key points
- ●A graph is just things and links: grid cells, courses with prerequisites, routers with cables.
- ●"Fewest steps" means BFS; "how many groups" means DFS.
- ●"Prerequisites" or an order means topological sort; "cheapest" with costs means Dijkstra.
- ●Links arriving one by one, with "already connected?" questions, means union-find.
- ●Always keep a visited set, and decide first whether links go one way or both ways.

First, spot the graph
A map of land and water. A list of college courses. A network of routers. Three LeetCode questions, and none of them says "graph". They all are.
A graph is just things and links between them:
- In a grid, every cell is a thing, linked to the cells up, down, left and right.
- In a course list, every course is a thing, and a prerequisite is a link.
- In a network, every router is a thing, and a cable with a delay is a link.
Write the links down as a list: for each thing, the things it points to. Keep a visited set too, because graphs have loops and without it you'll walk in circles.
Ask one question before you code: do the links go both ways, like roads, or one way, like a prerequisite? Get it backwards and the answer can look right on the example and fail everything else.
Move 1: breadth-first search (BFS)
Use it for: the shortest path, fewest steps or minimum moves, when every step costs the same.
BFS is a stone dropped in a pond. It checks everything one step away, then two steps, then three. So the first time it reaches a cell, that's the shortest way there. On a 3 by 3 grid, corner to corner takes 4 steps.
The queue is the trick: first in, first out, so closer cells come out first. Trap: using a plain list with pop(0), which shifts the whole list every time. Use a deque and popleft().
Twist: many starts. In Rotting Oranges, every rotten orange spoils its neighbors each minute. Don't run BFS once per rotten orange. Put them all in the queue at minute zero and let one ripple do the work. The answer is how many rings it takes to reach the last fresh orange, or -1 if one is never reached.
Move 2: depth-first search (DFS)
Use it for: counting groups, filling a region, or checking whether two things connect at all. Distance doesn't matter; reaching everything does.
Number of Islands. A grid of 1s (land) and 0s (water); land cells touching up, down, left or right form one island. Scan the map. When you hit land, add one to the count and then sink the whole island, turning every connected land cell to water so it can't be counted again. On the sheet's 4 by 4 map, the first land cell sinks a group of 3, the next land you hit is the group of 3 on the right: 2 islands. Every cell is looked at once, so it's O(rows × columns).
Traps: mark a cell before you visit its neighbors, or two neighbors can visit each other forever. And on a huge all-land grid, recursion can go thousands of calls deep, past Python's default limit of about a thousand. If the interviewer mentions a big grid, use your own stack instead.
Move 3: topological sort
Use it for: things that depend on other things, when you need an order or need to know if one exists.
Course Schedule. Each pair says one course comes before another. Can you finish them all? Count, for every course, how many prerequisites still block it, and start with the ones at zero. Take one; every course it unlocks loses a blocker, and anything that hits zero joins the queue.
A chain 0, 1, 2, 3 finishes all four: true. If course 0 needs 1 and 1 needs 0, neither ever reaches zero: false. Finishing fewer courses than you have means there's a cycle. This is the Python from the Course Schedule sheet:
from collections import deque
def can_finish(n, pairs):
graph = [[] for _ in range(n)]
indegree = [0] * n
for course, prerequisite in pairs:
graph[prerequisite].append(course)
indegree[course] += 1
queue = deque(c for c in range(n) if indegree[c] == 0)
completed = 0
while queue:
course = queue.popleft()
completed += 1
for next_course in graph[course]:
indegree[next_course] -= 1
if indegree[next_course] == 0:
queue.append(next_course)
return completed == n
It runs in O(n + p) for n courses and p pairs. For Course Schedule II, which wants the order itself, write down each course as it leaves the queue. There's also a DFS version that colors courses white, gray or black, where hitting a gray course again means a loop.
Move 4: Dijkstra's algorithm
Use it for: the cheapest path when steps cost different amounts, like cables with delays or flights with prices. It's BFS with costs.
Network Delay Time. A signal starts at one node and each directed edge takes some milliseconds. How long until every node has it? The rule: always settle the closest node you haven't settled yet. Costs can't be negative, so nothing later can beat it. Start at node 2 at time 0; nodes 1 and 3 get the signal at time 1, node 4 through node 3 at time 2. The slowest node decides: 2 ms. A min heap hands you the closest node in O(log n). If a node never gets reached, the answer is -1.
Trap: negative costs break the promise that nothing gets cheaper later. Interview questions almost never have them, but say it out loud. And if every edge costs the same, skip the heap: that's just BFS.
Move 5: union-find
Use it for: links that arrive one at a time while you keep asking "are these two already connected?"
Redundant Connection. Edges come in one by one; find the first one that makes a loop. Give every node a boss, starting with itself. For each edge, follow both nodes up to their top boss. Different bosses: merge the groups. Same boss: they were already connected, and that edge is the loop. With edges 1-2, then 1-3, then 2-3, the third edge finds the same boss and is the extra one.
Flattening the chain as you look up each boss keeps every lookup close to O(1). Rerunning DFS after every edge would also work, but on a big graph it's painfully slow.
Which move? A quick quiz
| Question | Clue | Move |
|---|---|---|
| Fewest knight moves on a chessboard | Every move costs one | BFS |
| Alien Dictionary | Letters depend on letters | Topological sort |
| Cheapest flights between two cities | Prices on every flight | Dijkstra (track stops too) |
| Number of Islands | How many groups | DFS |
| Redundant Connection | Edges arrive one by one | Union-find |
Next time a question hands you a grid, a list of pairs or a network, say it out loud: it's a graph. Then pick the move. The visual sheet above works Number of Islands with DFS, sinking each island as it counts it.
Frequently asked questions
How do I recognize a graph problem when it doesn't say graph?
Look for things and links between them. A grid of land and water links each cell to its four neighbors, a list of course pairs links prerequisites to courses, and a network links routers with delayed cables. If you can list, for each thing, the things it points to, it's a graph.
When should I use BFS instead of DFS?
Use BFS when the question asks for the shortest path, fewest steps or minimum moves and every step costs the same, because the first time BFS reaches a node is the shortest way there. Use DFS when distance doesn't matter and you only need to reach everything, like counting islands.
Why doesn't Dijkstra work with negative edge costs?
Dijkstra settles the closest unsettled node and treats it as final, which is only safe if nothing can get cheaper later. A negative cost breaks that promise, so a node settled early could have had a cheaper path.
What is union-find used for in interviews?
For questions where edges arrive one at a time and you keep asking whether two nodes are already connected, like Redundant Connection. Each node follows a chain up to its top boss; same boss means already connected, so the new edge makes a loop.