Graphs
Reach for it when the problem says
- Grids
- networks
- dependencies
- shortest path
- islands
- Solved
- 0/33Solved
- Problems
- 33Problems
- Variants
- 6Variants
Problems
6 variantsGrid flood fill
0 of 5 solved- Flood FillUp nextDeep diveEasyDecode Flood Fill
- Number of IslandsSprintDeep diveMediumDecode Number of Islands
- Max Area of IslandMediumDecode Max Area of Island
- Surrounded RegionsSprintDeep diveMediumDecode Surrounded Regions
- Pacific Atlantic Water FlowMediumDecode Pacific Atlantic Water Flow
BFS shortest path
0 of 7 solved- Rotting OrangesEssentialsDeep diveMediumDecode Rotting Oranges
- Walls and GatesMediumDecode Walls and Gates
- Nearest Exit from Entrance in MazeEssentialsDeep diveMediumDecode Nearest Exit from Entrance in Maze
- Shortest Path in Binary MatrixMediumDecode Shortest Path in Binary Matrix
- Snakes and LaddersSprintDeep diveMediumDecode Snakes and Ladders
- Minimum Genetic MutationSprintDeep diveMediumDecode Minimum Genetic Mutation
- Word LadderSprintDeep diveHardDecode Word Ladder
Topological sort
0 of 3 solved- Course ScheduleSprintDeep diveMediumDecode Course Schedule
- Course Schedule IISprintDeep diveMediumDecode Course Schedule II
- Alien DictionaryDeep diveHardDecode Alien Dictionary
Union-find
0 of 4 solvedWeighted graphs
0 of 5 solved- Network Delay TimeMediumDecode Network Delay Time
- Min Cost to Connect All PointsMediumDecode Min Cost to Connect All Points
- Cheapest Flights Within K StopsMediumDecode Cheapest Flights Within K Stops
- Path With Minimum EffortMediumDecode Path With Minimum Effort
- Swim in Rising WaterDeep diveHardDecode Swim in Rising Water
Graph traversal
0 of 9 solved- Find if Path Exists in GraphDeep diveEasyDecode Find if Path Exists in Graph
- Find the Town JudgeDeep diveEasyDecode Find the Town Judge
- Clone GraphSprintDeep diveMediumDecode Clone Graph
- Keys and RoomsEssentialsDeep diveMediumDecode Keys and Rooms
- Number of ProvincesEssentialsDeep diveMediumDecode Number of Provinces
- Reorder Routes to Make All Paths Lead to the City ZeroEssentialsDeep diveMediumDecode Reorder Routes to Make All Paths Lead to the City Zero
- Evaluate DivisionEssentialsSprintDeep diveMediumDecode Evaluate Division
- Is Graph Bipartite?MediumDecode Is Graph Bipartite?
- Reconstruct ItineraryDeep diveHardDecode Reconstruct Itinerary
Pattern guide
Graph problems are the largest single family in interviews, and they rarely say "graph". They say islands, courses, flights, accounts, oranges or words. The skill that pays off is seeing the nodes and edges inside the story, because once you do, five or six well-known templates cover almost everything.
What it is
A graph is a set of nodes (also called vertices) joined by edges. Edges can be undirected (a road you can drive both ways) or directed (a one-way flight, a prerequisite), and they can be unweighted or carry a weight (a price, a delay, a height difference). V is the number of nodes and E the number of edges.
Almost every graph algorithm is the same loop with a different container. You keep a frontier of nodes you have discovered but not yet expanded, and a visited set so that cycles cannot trap you. Pop a node, look at its neighbours, add the new ones to the frontier. A stack gives you DFS (depth-first search), a queue gives you BFS (breadth-first search), and a min-heap gives you Dijkstra.
Start at S with distance 0. Mark it visited as it enters the queue, not when it leaves.
That last sentence is the reason BFS matters: in an unweighted graph, the first time BFS touches a node is along a shortest path. DFS gives no such promise, but it is simpler to write and is all you need when the question is only "can I reach it?" or "how many groups are there?".
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "grid", "map", "island", "region", "up, down, left or right" | A grid graph: each cell is a node with up to four edges |
| "connected", "group", "province", "component" | Count or label connected components (DFS or union-find) |
| "minimum number of steps", "shortest", "fewest moves", "minutes until" | BFS on an unweighted graph |
| "nearest", "from every gate", "all rotten oranges at once" | Multi-source BFS: start with every source in the queue |
| "prerequisite", "before", "depends on", "order of tasks" | Directed graph plus topological sort |
| "cycle", "redundant", "valid tree" | Cycle detection: union-find for undirected, colours or Kahn's for directed |
| "cheapest", "price", "delay", "cost", "effort" with numbers on edges | Weighted shortest path: Dijkstra, or Bellman-Ford with a hop limit |
| "connect all", "minimum total cost to connect" | Minimum spanning tree (Prim or Kruskal) |
| "deep copy", "clone" | Traversal plus a map from original node to copy |
Constraint clues
| Constraint | What it tells you |
|---|---|
Grid up to 300 x 300 or 250 x 250 | Up to 90,000 cells: O(rows · cols) only. Prefer an explicit stack to deep recursion |
n <= 2 * 10^5 nodes and edges | O(V + E) with an adjacency list; a V by V matrix would not fit |
n <= 100 or n <= 200 given as a matrix | O(n²) or even O(n³) is fine; the input itself is n² |
Weights >= 0 | Dijkstra is safe |
A limit like "at most k stops" | Plain Dijkstra breaks; use Bellman-Ford rounds or a (node, stops) state |
edges.length == n - 1 or == n | A tree, or a tree plus exactly one extra edge |
points.length <= 1000, every pair is an edge | A dense graph: array-based Prim's in O(n²) |
Input and output shape clues
| Shape | Likely sub-pattern |
|---|---|
| 2D grid in, a count or an area out | Grid flood fill |
| Grid or word list in, a number of steps out | BFS shortest path |
Edge list or adjacency list in, true/false or a count out | Graph traversal or union-find |
Pairs [a, b] meaning "b before a", an order out | Topological sort |
| Edges arriving one by one, "which edge" or "how many groups" out | Union-find |
Triples [u, v, w] or a height grid, a cost out | Weighted graphs |
Looks like it but isn't
- Grid does not mean dynamic programming. If movement is only right and down, a DP table works. If you can move in all four directions, paths can loop back, there is no fill order, and you need a graph search.
- Trees are graphs with a guarantee. If the input is an edge list with a possible cycle, tree recursion without a visited set will loop forever. Clone Graph is the classic trap.
- "Shortest" with weights is not BFS. BFS counts edges. The moment edges have different costs, a two-hop detour can beat one slow direct edge, and you need Dijkstra.
- Greedy nearest-neighbour is not an MST. Linking each point to its closest neighbour can leave separate clusters. Prim's and Kruskal's are greedy, but in a specific, provably correct way.
Match each prompt phrase to the tool it points at.
The sub-patterns
Grid flood fill
When it applies: the input is a grid and the question is about connected regions: count them, measure them, recolour them, or find the cells that can reach an edge. Each cell is a node, and its four side neighbours are its edges. You never build an adjacency list; four (dr, dc) offsets and a bounds check do the job.
The move is always the same. Scan every cell. When you meet a cell that starts a new region, flood it with DFS or BFS and mark what you reach, often by overwriting the grid itself. For "which cells can reach the border" questions, flip it around and flood from the border inward.
Scan from the top-left. (0,0) is land nobody has visited: island 1. Start a flood here.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(rows · cols) time, O(rows · cols) space for the stack in the worst case (one huge region).
Best-known problems: Number of Islands, Max Area of Island, Flood Fill, Surrounded Regions, Pacific Atlantic Water Flow.
BFS shortest path
When it applies: you need the fewest steps, moves or minutes, and every step costs the same. BFS explores in rings of equal distance, so the first time it reaches a cell or word, that is the shortest distance. Process the queue one layer at a time when the answer is "how many layers" (minutes, steps).
The most useful twist is multi-source BFS: when the question says "nearest of many" (nearest gate, every rotten orange at once), put every source in the queue at distance 0 before you start. One BFS then gives every cell its distance to the closest source.
Minute 0. The only rotten orange (2) seeds the queue. Count fresh oranges up front: 6.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The TypeScript version uses a growing array with a head index instead of shift(), because shift() is O(n) and turns BFS quadratic on big inputs.
Complexity: O(V + E), which on a grid is O(rows · cols). For word ladders, generating neighbours costs 26 · L per word.
Best-known problems: Rotting Oranges, Walls and Gates, Word Ladder, Shortest Path in Binary Matrix, Nearest Exit from Entrance in Maze.
What does this print?
from collections import deque
graph = {0: [1, 2], 1: [3], 2: [3, 4], 3: [5], 4: [5], 5: []}
dist = {0: 0}
queue = deque([0])
while queue:
node = queue.popleft()
for nxt in graph[node]:
if nxt not in dist:
dist[nxt] = dist[node] + 1
queue.append(nxt)
print(dist[5], len(dist))Graph traversal
When it applies: the graph is given explicitly (an edge list, an adjacency list, an adjacency matrix, or node objects) and the question is about reachability, components, copying, colouring or walking every edge. You build an adjacency list, then run DFS or BFS with a visited set. What you do at each node is the part that changes.
- Reachability: can you get from
stot? Can room 0 reach every room? - Components: count how many traversals you have to start (Number of Provinces).
- Copying: keep a map from original node to copy (Clone Graph).
- Colouring: give neighbours opposite colours and look for a clash (Is Graph Bipartite?).
- Edge tags: store extra data on each edge, like a direction flag (Reorder Routes) or a ratio (Evaluate Division).
- Every edge once: post-order DFS that writes a node down when it runs out of edges (Reconstruct Itinerary).
Colour node 0 with A. Its neighbours are now forced to be B.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(V + E) time, O(V + E) space for the adjacency list. With an adjacency matrix it is O(V²), because reading a node's row costs V.
Best-known problems: Clone Graph, Number of Provinces, Keys and Rooms, Is Graph Bipartite?, Evaluate Division, Reconstruct Itinerary.
true if it finds no clash. Which input breaks it?Topological sort
When it applies: a directed graph of dependencies ("b before a") where you must produce an order that respects every edge, or decide that no order exists. An order exists exactly when the graph has no cycle (a DAG, directed acyclic graph).
Kahn's algorithm is the version to reach for first. Count each node's in-degree (how many arrows point into it). Every node with in-degree 0 has nothing blocking it, so queue it. Pop a node, append it to the order, and lower the in-degree of everything it points at; anything that drops to 0 joins the queue. If the order ends up shorter than the number of nodes, the leftovers sit on a cycle.
Count in-degrees. Only course 0 has none, so it is the only one in the queue.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.The alternative is DFS with three colours (unvisited, in progress, done): reaching an "in progress" node means a cycle, and appending nodes when they finish, then reversing, gives a topological order. Both are O(V + E); Kahn's is easier to get right under pressure.
Complexity: O(V + E) time and space.
Best-known problems: Course Schedule, Course Schedule II, Alien Dictionary.
Put the steps of Kahn's algorithm in order.
- Tap the steps below in the right order.
Union-find
When it applies: you care about which group each node is in, edges arrive as a list (often one at a time), and you want to merge groups or detect the edge that closes a cycle in an undirected graph. Union-find (also called disjoint set union, DSU) keeps a parent array where each group is a little tree; the root names the group.
Two operations do everything. find(x) walks up to the root, and path compression shortcuts the walk so later finds are nearly instant. union(a, b) links one root under the other. If find(a) == find(b) before a union, a and b were already connected, so the edge between them is redundant: it closes a cycle.
Every node is its own parent: six groups of one. Index is the node, value is its parent.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: each operation is O(α(n)), the inverse Ackermann function, which is at most 4 for any input you will ever see. So E edges cost about O(E). Add union by size or rank for the textbook guarantee; path compression alone is plenty in interviews.
Best-known problems: Number of Connected Components, Graph Valid Tree, Redundant Connection, Accounts Merge.
Weighted graphs
When it applies: edges carry a cost and you want the cheapest route, the route with the smallest worst step, or the cheapest way to connect everything. Three tools cover nearly every case:
| Situation | Tool | Time |
|---|---|---|
Shortest path, weights >= 0 | Dijkstra with a min-heap | O(E log V) |
| Path cost is the maximum edge or cell (effort, rising water) | Dijkstra with max instead of + | O(E log V) |
| A limit on the number of edges ("at most k stops") | Bellman-Ford for k + 1 rounds | O(k · E) |
| Connect every node as cheaply as possible | Prim's (dense) or Kruskal's with union-find (sparse) | O(V²) or O(E log E) |
Dijkstra's key fact: when all weights are non-negative, the unsettled node with the smallest tentative distance can never get cheaper, so you can settle it for good. A heap hands you that node in O(log V). Old heap entries for a node you already settled are simply skipped when popped.
Settle S at 0. Tentative distances: A = 4, B = 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.In TypeScript interviews, say out loud that there is no standard heap: either write a 25-line binary heap, or use the O(V²) scan when V is small (a few thousand at most). Both are accepted answers.
Complexity: O(E log V) with a heap, O(V²) with the array scan. Bellman-Ford is O(k · E) with a hop limit and O(V · E) without one.
Best-known problems: Network Delay Time, Cheapest Flights Within K Stops, Path With Minimum Effort, Swim in Rising Water, Min Cost to Connect All Points.
Decision checklist
Ask these in order. The first "yes" usually names the sub-pattern.
- Is the input a grid and the question about regions? Grid flood fill.
- Do you need the fewest steps with every step costing the same? BFS shortest path (multi-source if there are many starts).
- Do edges say "before" or "depends on"? Topological sort.
- Are you merging groups, or hunting the edge that closes a cycle in an undirected graph? Union-find.
- Do edges or cells carry costs you add up, take the max of, or must connect cheaply? Weighted graphs.
- Otherwise: build an adjacency list and run a graph traversal, deciding what to do at each node.
Match each problem to its sub-pattern.
Traps
- Marking visited too late. Mark when you push, not when you pop. Late marking queues duplicates and, in grid BFS, can produce wrong layer counts.
- Forgetting both directions. For an undirected edge list, add
btoa's list andatob's list. Missing one makes half the graph unreachable. - Only starting from node 0. Components, bipartite checks and topological sorts must loop over every node, because the graph may be disconnected.
- Recursion depth. A 300 by 300 grid of land is 90,000 nested calls. Python's default limit is 1000. Use an explicit stack or a queue.
queue.shift()in JavaScript. It is O(n), so BFS becomes O(n²). Use a head index into an array.- Same colour flood fill. In Flood Fill, if the new colour equals the old one, painted cells still match and the fill never ends. Return early.
- BFS on weighted edges. BFS counts edges, not cost. If weights differ, use Dijkstra.
- Off-by-one in counting. Word Ladder counts words, not steps, so it starts at 1. Shortest Path in Binary Matrix counts cells, so a 1 by 1 grid answers 1. Rotting Oranges with nothing fresh answers 0, not 1.
Edge cases to always test: an empty or single-node graph, a graph with no edges, a disconnected graph, a self-loop or two-node cycle, duplicate edges, and the largest input (for recursion depth).
n = 4, edges = [[0, 1], [1, 2], [2, 0]]. A Graph Valid Tree solution only checks len(edges) == n - 1. What does it return, and is that right?How to talk it through
A model narration for Rotting Oranges: "Each cell is a node with four neighbours. Rot spreads from every rotten orange at once, one step a minute, so minutes are BFS layers from all the rotten oranges together. I'll queue every rotten orange, count fresh ones, and process one layer per minute, rotting neighbours and decrementing the count. When the queue empties, I return the minutes if nothing fresh is left, otherwise minus one. Each cell is queued once, so it's O(rows times cols)."
- Adjacency list
- For each node, the list of its neighbours. O(V + E) space, the default way to store a sparse graph.
- Connected component
- A maximal group of nodes that can all reach each other. Counting islands or provinces is counting components.
- Multi-source BFS
- BFS that starts with every source in the queue at distance 0, giving each node its distance to the nearest source in one pass.
- Topological order
- An ordering of a directed graph's nodes where every edge points forward. It exists only when the graph has no cycle.
- Union-find
- A parent array that tracks groups.
findreturns a group's root,unionmerges two groups, and equal roots before a union reveal a cycle. - Dijkstra's algorithm
- Shortest paths with non-negative weights: repeatedly settle the closest unsettled node using a min-heap. O(E log V).