Skip to content

Software interviews

Graph problems for coding interviews: BFS, DFS and practice

A graph problem gives you things and the links between them, such as routes, grid cells or tasks with prerequisites, and almost every one yields to a traversal. Breadth-first search uses a queue and finds the fewest edges, and depth-first search uses a stack or recursion and explores one branch fully. Both run in time proportional to the nodes plus the edges when the graph is stored as adjacency lists. This page explains how to choose, the signals, the edge cases and four original problems with recomputed answers.

Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.

Book your first hour ($250)

What the technique is and what it costs

A graph is a set of nodes and a set of edges between them. The edges may have a direction, as a prerequisite does, or none, as a road does. Two things decide your approach: how the graph is stored, and which traversal you run on it.

Open Data Structures describes two storage choices. An adjacency matrix holds an n by n table of true and false values, one per pair of nodes. Adding, removing or testing an edge takes constant time, but listing the neighbors of a node takes O(n) time, and the table uses on the order of n squared memory. Adjacency lists keep, for each node, a list of its neighbors, and the book states that the structure uses O(n + m) space, adds an edge in constant time and tests an edge in time proportional to the node’s degree.

For traversal, NIST defines breadth-first search as a search that considers the neighbors of a vertex before any of the neighbors’ own neighbors, typically implemented with a queue, and notes that on a tree it is a level-order traversal. It defines depth-first search as one that considers the children of a vertex before any of the vertex’s siblings, easily implemented with recursion. Open Data Structures shows both running in O(n + m) time on adjacency lists, because each node is processed once and each edge at most once. It also warns that a recursive depth-first search can fail on a large graph by overflowing the stack, and that an explicit stack avoids this.

Storage costs, from the sources
QuestionAdjacency matrixAdjacency lists
MemoryAbout n squared entriesAbout n + m entries
Is there an edge from i to jConstant timeTime proportional to the degree of i
List the neighbors of iO(n)Time proportional to the degree of i
Best forDense graphs, where m is close to n squaredSparse graphs, which is most of what interviews use

To see why the storage choice matters, compare the memory for three sizes of sparse graph. These are made-up sizes for the arithmetic, with about three to four edges per node.

Matrix entries against list entries, for sparse graphs of three sizes
Nodes (n)Edges (m)Matrix entries (n squared)List entries (n + m)Matrix size as a multiple of list size
1,0003,0001,000,0004,000250 times
100,000300,00010,000,000,000400,00025,000 times
1,000,0004,000,0001,000,000,000,0005,000,000200,000 times

For a million nodes, the matrix would need about a trillion entries. This is why a grid or a road map is treated as adjacency lists, or as no explicit storage at all, since a grid cell’s neighbors are computed from its row and column. MIT OpenCourseWare’s 6.006 course page describes common algorithms, algorithmic paradigms and data structures, with basic performance measures and analysis techniques, and is a reference for the same material.

The problem signals that call for a traversal

Signals in a problem statement and the technique each calls for
Signal in the statementWhat it usually meansTechnique
“Fewest steps,” “shortest path” with equal edges, “minimum moves”The nearest by edge countBFS from the start, counting levels
“How many groups,” “connected,” “islands”Count the pieces of a graph or a gridTraverse from each unvisited node and count the starts
“Can you reach,” “is there a path”ReachabilityEither traversal from the start
“Order the tasks,” “prerequisites,” “can all be completed”A directed graph and an orderingCount incoming edges and schedule with a queue, or DFS with colors
“Is there a cycle”A walk that returnsDFS with colors in a directed graph; union-find or DFS in an undirected graph
A grid of cellsA graph with implicit edgesNeighbors by row and column moves, within the bounds

Pattern 1: breadth-first search for the fewest edges

Put the start in a queue at distance 0, mark it seen, then repeat: take the front node, look at its neighbors and, for each unseen one, mark it seen, record distance plus one and add it to the queue. Because the queue holds nodes in order of distance, the first time you reach a node is by a shortest path. Our first problem asks for the fewest edges between two nodes in a small undirected graph.

Pattern 2: counting components and islands

To count groups, scan every node. When you meet one you have not seen, add one to the count and traverse everything reachable from it, marking as you go. In a grid, the neighbors are the cells above, below, left and right, and the problem usually says whether diagonals count. Our second problem counts components in a list of edges, including a node with no edges, and our third counts islands in a grid where touching at a corner does not join cells.

Pattern 3: ordering with prerequisites

When edges mean this must come before that, count each node’s incoming edges. Queue the nodes with none, and each time you schedule a node, lower the count of every node it points to and queue any that reach zero. If every node is scheduled there is a valid order, and if some are not, they lie on a cycle or are reached from one. Our fourth problem counts how many nodes can be scheduled when a cycle is present.

Edge cases interviewers probe

  • A disconnected graph. A single traversal from one node misses the other pieces, so loop over all nodes.
  • Nodes with no edges. They are components of their own and they never appear in an edge list.
  • Directed against undirected. For an undirected edge, add both directions.
  • Repeated edges and self loops. They should not change a component count or a shortest path.
  • Marking time in BFS. Mark when you add to the queue, not when you remove, or the same node can enter several times.
  • Grid bounds and diagonals. Check the row and column are inside the grid, and ask whether diagonal moves count.
  • Deep recursion. A long path can overflow the stack in a recursive DFS, so know how to write it with an explicit stack.

Four practice problems, in order of difficulty

These are our own practice problems. Try each on paper first, then open the working. They run from a shortest path to an ordering with a cycle. These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.

Problem 1. An undirected graph has nodes 0 to 8 and these edges: 0-1, 0-2, 1-3, 2-3, 3-4, 2-5, 5-6, 4-7, 6-7, 7-8, 5-8. What is the fewest number of edges on a path from node 0 to node 8? Give an integer.

Show the answer and the working

Answer: 3

  1. When every edge counts the same, breadth-first search finds the fewest edges, because it visits every node at distance 1, then every node at distance 2, and so on, with a queue.
  2. Start with node 0 at distance 0. Its neighbours 1 and 2 are at distance 1. From them, nodes 3 and 5 are at distance 2, since 1 reaches 3 and 2 reaches both 3 and 5.
  3. From distance 2, node 8 is a neighbour of node 5, so node 8 is at distance 3. Nodes 4 and 6 are also at distance 3 and node 7 is at distance 4 through node 4 or node 6.
  4. The shortest path is 0, 2, 5, 8, which is 3 edges. No path of 2 edges exists, because node 8 is not a neighbour of node 1 or node 2, the only nodes at distance 1. Breadth-first search runs in O(n + m) with adjacency lists.

Problem 2. An undirected graph has nodes 0 to 10 and these edges: 0-1, 1-2, 3-4, 5-6, 6-7, 7-5, 8-9, 2-0, 4-3. How many connected components does it have, counting a node with no edges as a component of its own? Give an integer.

Show the answer and the working

Answer: 5

  1. Pick a node you have not visited, explore everything reachable from it with a depth-first or breadth-first search, and count one component. Repeat until every node is visited.
  2. Starting at 0 reaches 1 and 2, and the edge 2-0 closes a triangle inside the same component, so the first component is 0, 1, 2. Starting at 3 reaches 4, and the edge 4-3 repeats the edge 3-4. Starting at 5 reaches 6 and 7, and the edge 7-5 closes a triangle inside the same component.
  3. Starting at 8 reaches 9. Node 10 appears in no edge, so it is a component of its own.
  4. That makes {0, 1, 2}, {3, 4}, {5, 6, 7}, {8, 9} and {10}, which is 5 components. The easy slips are forgetting the isolated node and counting a repeated edge as a new link. The work is O(n + m).

Problem 3. A grid has 5 rows and 7 columns. Its rows, from top to bottom, are 1101000, 1100110, 0001110, 1000001, 1011011, where 1 is land and 0 is water. Land cells that share an edge, meaning up, down, left or right, belong to the same island. Cells that touch only at a corner do not. How many islands are there? Give an integer.

Show the answer and the working

Answer: 6

  1. Scan the grid cell by cell. At each land cell you have not seen, count one island and run a flood fill that marks every land cell reachable by up, down, left and right moves.
  2. The top left block of four cells, rows 0 and 1 and columns 0 and 1, is the first island. The single land cell at row 0, column 3 has water or the grid edge on every side, so it is an island of its own. It touches the land at row 1, column 4 only at a corner, which does not join them.
  3. The land at rows 1 and 2 around columns 3 to 5 joins into one island of 5 cells. The two cells in column 0, rows 3 and 4, form another. The three cells at the lower right, row 3 column 6 and row 4 columns 5 and 6, form another. The two cells at row 4, columns 2 and 3, form the last.
  4. That is 6 islands. Each cell is visited once, so the scan is O(rows x columns). Using an explicit stack or queue avoids a deep recursion on a large grid.

Problem 4. A directed graph has nodes 0 to 8 and these edges, each written from-to: 0 to 1, 1 to 2, 2 to 3, 3 to 1, 0 to 4, 4 to 5, 6 to 7, 7 to 8, 5 to 3, 8 to 4. A node can be scheduled once every node with an edge into it has been scheduled, and a node with no incoming edges can be scheduled at once. How many nodes can be scheduled in total? Give an integer.

Show the answer and the working

Answer: 6

  1. Count the incoming edges of each node. Put the nodes with none in a queue, and each time you schedule a node, lower the count of every node it points to, queueing any node whose count reaches 0.
  2. Nodes 0 and 6 have no incoming edges. Scheduling 0 lowers node 1 and node 4. Node 1 still waits on node 3, and node 4 still waits on node 8. Scheduling 6 frees node 7, then node 7 frees node 8, and node 8 frees node 4.
  3. Node 4 frees node 5. Node 5 points to node 3, but node 3 also waits on node 2, which waits on node 1, which waits on node 3. Nodes 1, 2 and 3 form a cycle, so none of them reaches a count of 0.
  4. The nodes scheduled are 0, 6, 7, 8, 4 and 5, which is 6. Nodes 4 and 5 lead into the cycle but are not stuck by it, because only a node on a cycle, or a node reached from one, waits forever. The pass is O(n + m).

Every answer above is recomputed by a separate program when the site is built, and the program rebuilds each result by a different route from the written steps. A wrong answer would stop the build.

A longer ladder of graphs problems

Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 17 problem types that interviewers often use for graphs into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.

Graphs problem types in three sets, with a count of each
SetTypesProblems to look upWhat the set trains
Easy3finding the one person everyone trusts; whether a path exists between two nodes; the center of a star-shaped graphBuilding the graph and walking it once
Medium9course ordering with prerequisites; copying a graph; whether a graph is a tree; counting connected components; a cheapest route with limited stops; two-coloring a graph; shortest times through a network; rooms you can reach with keys; detecting a redundant edgeChoosing between BFS, DFS, union-find and a shortest-path method
Hard5the order of letters in an unknown alphabet; critical connections in a network; the shortest walk that visits every node; the longest increasing path in a grid; ordering items that depend on each other in groupsCombining a traversal with state, such as a set of visited nodes

Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.

Before any code, say how the input becomes a graph: what a node is, what an edge is and whether it points one way. Many graph problems hide inside grids, words and dependency lists. Naming the nodes and edges aloud is the step that turns a puzzle into a known pattern.

Questions

When should I use BFS instead of DFS?

Use breadth-first search when you want the fewest edges from a start, because it visits every node at distance 1, then every node at distance 2, and so on. Use depth-first search when you need to explore a whole branch, as in finding components, detecting cycles or ordering tasks.

What is the running time of BFS and DFS?

Open Data Structures shows both run in O(n + m) time on a graph stored as adjacency lists, where n is the number of nodes and m is the number of edges.

Should I mark a node visited when I add it or when I remove it?

In BFS, mark it when you add it to the queue. Marking at removal lets the same node enter the queue several times and wastes time, and in a grid it can multiply the work.

How a session helps

A session with George is a place to work a problem aloud and have the reasoning questioned. You write every line of code and every answer yourself. An hour is $250, and a package of 5 sessions is $1,165 for a full interview season. Your first purchase is refundable for unused time within 7 days. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to space your practice. The college students page and the packages page list the sessions.

Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.

Start with one hour

  • Your first purchase is refundable for unused time within 7 days. Nothing renews. Refund terms