iq.lab
Python starts when a code cell comes near or you run one
10 Graphs

Lesson 1 of 6

What a graph is

A graph is a set of things joined by connections. Problems hand you one as a list of edges or as a grid. You turn the edges into an adjacency list so a node's neighbors cost one lookup, and you spread out from a start with a set and a stack to find everything it can reach.

About 1 hour 10 minutes, with the problem worked in it
By the end you can
  • Say whether a graph is directed or undirected, weighted or unweighted, from a description of it

  • Build an adjacency list from an edge list with defaultdict(list), adding both directions for a two-way edge

  • List the neighbors of a grid cell with a directions list and a bounds check

  • Find every node reachable from a start with a seen set and a todo stack

  • State the cost of building and searching a graph as O(n + E)

You run a small pipeline. A table of raw orders, raw, feeds a cleaned table, clean. Two tables are built from clean: daily totals and top customers. A report reads both of those, plus an ads table from another team. One morning raw arrives broken. Which tables are now wrong?

No single table holds the answer. It lives in the connections: clean reads raw, daily reads clean, and so on down the line. Things plus the connections between them make a graph, and "what does this break?" is a question about walking one.

Interview problems are full of graphs, often in disguise: courses with prerequisites, a map of land and water, a maze. This lesson builds the base for the whole module: the words, the two ways a problem hands you a graph (a list of edges or a grid), the structure you build from the edges, and a first search that answers "what can I reach from here?".

Nodes and edges

What exactly is a graph? A graph is a set of nodes joined by edges. A node (also called a vertex) is one thing: a table, a person, a city. An edge connects two nodes. Here is the pipeline from the opening, with an arrow from each table to every table built from it:

raw --> clean --> daily --> report <-- ads
          |                   ^
          +-----> top --------+

The arrows make this a directed graph: each edge goes one way. clean is built from raw, not the other way around. A friendship is different: if Ana is friends with Ben, Ben is friends with Ana. An undirected graph has two-way edges, drawn as plain lines. An edge can also carry a number, called its weight: the length of a road, the price of a flight. A graph whose edges carry numbers is weighted. This lesson and the next four use unweighted graphs; the last lesson of the module adds weights.

Four more words, each used all through this module:

  • The neighbors of a node are the nodes one edge away. In a directed graph, follow the arrows out: the neighbors of clean are daily and top, not raw.
  • A path is a chain of nodes where each step follows an edge, such as raw, clean, top, report.
  • A cycle is a path that comes back to where it started without using any edge twice. This pipeline has none. Add an arrow from report back to raw, and raw, clean, daily, report, raw would be one.
  • A node is reachable from another when some path leads to it. report is reachable from raw. ads is not: its only edge points away from it, into report. A node also counts as reachable from itself, by a path of no steps.

Most problems describe the graph in words, so the first job is to name its kind.

Quick checkName the graph

A university lists its course prerequisites as pairs: [0, 1] means you must take course 0 before course 1. Make each course a node and each pair an edge. What kind of graph is it?

Choose one answer, then check.

The adjacency list

How do you find the neighbors of a node? Problems often hand you an edge list: the nodes are numbered 0 to n − 1, so there are n of them, and each pair in edges is one edge. With only the edge list, finding one node's neighbors means reading every edge and keeping the ones that touch it. That is O(E) work for one question, where E is the number of edges. A search asks that question for every node it reaches, so a search that reaches all n nodes costs O(n × E).

An adjacency list stores each node's neighbors in a list of its own, so the question becomes one lookup. In Python it is a dict from each node to the list of its neighbors, built in one pass over the edges. The tool for the job, as a reminder from module 3: defaultdict(list) is a dict that stores a new empty list the first time you read a missing key, so graph[a].append(b) works whether or not a has appeared before.

Here are n = 4 and edges = [[0, 1], [1, 2], [2, 0], [2, 3]], two-way edges, drawn with plain lines:

0 --- 1
 \   /
  \ /
   2 --- 3

Every two-way edge goes into two lists: [0, 1] lets you step from 0 to 1 and from 1 back to 0. Before you step through, guess the list for node 2, in order.

Step throughFrom an edge list to an adjacency list
Step 1 of 18
Line 1 is about to run.
from collections import defaultdict
edges = [[0, 1], [1, 2], [2, 0], [2, 3]]
graph = defaultdict(list)
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
print(dict(graph))
Names
no names yet
Output
(nothing printed yet)

Here is the builder in the four questions:

For a directed graph, append once. An edge [a, b] that goes from a to b adds b to the list of a and nothing to the list of b. So in a directed graph, a node's list holds only the nodes its arrows point to.

Try a directed one. Predict it before you run it.

PredictA one-way adjacency list

Each pair [a, b] is a one-way edge from a to b. Type exactly what this prints, on two lines.

from collections import defaultdict

edges = [[0, 1], [0, 2], [2, 1], [3, 0]]
graph = defaultdict(list)
for a, b in edges:
    graph[a].append(b)
print(dict(graph))
print(graph[1])

Now write the builder yourself, with every node present.

Code itBuild an adjacency list

Write build_graph(n, edges). The nodes are numbered 0 to n − 1, and each [a, b] in edges is a two-way edge. Return a dict that maps every node, including nodes with no edges, to the list of its neighbors, in the order their edges appear in edges. Then press Watch it run to see the lists fill.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.

The other way to store a graph is an adjacency matrix: an n by n grid where row a, column b says whether an edge joins a to b. It answers "is there an edge from a to b?" in one step, but it always takes n2 cells, however few edges there are. The problem at the end of this lesson allows 2 × 105 nodes and 2 × 105 edges: a matrix would need 4 × 1010 cells, while the lists need at most 2 × 105 keys and 4 × 105 entries. Some problems hand you a matrix anyway (number of provinces, later in this module, does), and then you read it as it comes.

Recap: a graph usually arrives as an edge list. One pass turns it into an adjacency list: two appends for a two-way edge, one for a one-way edge. After that, a node's neighbors cost one lookup.

A grid is a graph

What if a problem never mentions edges? Many interview graphs come as a grid: a map of land and water, a maze, an image. Each cell is a node, and its neighbors are the cells directly up, down, left and right of it. Write a cell as (row, column), so (0, 1) is row 0, column 1. Diagonal cells do not count unless the problem says they do.

Each move to a neighbor changes the row or the column by one. Write a move as (change in row, change in column). Row 0 is the top row and the row number grows going down, so down is (1, 0), up is (−1, 0), right is (0, 1) and left is (0, −1). Put the four moves in a list called directions, and "the four neighbors" becomes one loop: add each move to the cell (r, c) to get a candidate (nr, nc), short for new row and new column.

Cells on the border have fewer than four neighbors, so every candidate needs a bounds check: 0 <= nr < rows and 0 <= nc < cols. Here rows is the number of rows, len(grid), and cols is the number of columns, len(grid[0]), the length of the first row. A reminder from module 1: a chained comparison such as 0 <= nr < rows means 0 <= nr and nr < rows.

The trace lists the neighbors of cell (0, 1), the "b" in the top row of a grid with 3 rows and 4 columns. Each cell holds a letter, so you can name a cell by its letter as well as by its position. Before you step through, guess how many neighbors it has.

Step throughThe neighbors of one cell
Step 1 of 23
Line 1 is about to run.
def neighbors(grid, r, c):
rows, cols = len(grid), len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
found = []
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols:
found.append((nr, nc))
return found
Names
no names yet
Output
(nothing printed yet)
Work it outA corner cell

A grid has 3 rows and 4 columns. How many neighbors (up, down, left or right, inside the grid) does the cell (2, 0) have? Type a whole number.

neighbors

Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

Most grid problems add a rule about which neighbors count: only open cells in a maze, only land on a map. That rule is one more condition, joined with and after the bounds check. The order matters: and stops at the first false part, so the cell is read only when it is inside the grid.

Put in orderCount the open neighbors

A maze is a list of strings, one per row: "." is an open cell and "#" is a wall, so grid[r][c] is one character. Put the lines in order to build open_neighbors(grid, r, c), which counts the open cells up, down, left and right of (r, c). Indentation is already part of each line. Two of the lines do not belong.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • for dr, dc in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
    • if grid[nr][nc] == "." and 0 <= nr < len(grid) and 0 <= nc < len(grid[0]):
    • count = 0
    • count += 1
    • def open_neighbors(grid, r, c):
    • if grid[nr][nc] == ".":
    • nr, nc = r + dr, c + dc
    • return count
    • if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == ".":

    A grid never needs an adjacency list. The neighbors come from arithmetic, at most four per cell, so finding them costs O(1) per cell. The grid in the trace, 3 rows by 4 columns, is a graph with 12 nodes; in general a grid has rows × cols nodes.

    What can you reach?

    Back to the opening question: if raw breaks, which tables are affected? Exactly the tables reachable from raw. Spread out from the start: reach its neighbors, then their neighbors, until nothing new turns up. Two notes keep the spread in order:

    • seen, the set of every node reached so far. It starts as {start}. A node goes in the moment it is first reached, so it never joins todo twice.
    • todo, a stack of reached nodes whose neighbors are not checked yet. A stack, from module 5, is a list used only at its end: append pushes an item on top, and pop() takes the newest item off.

    Each round pops one node and checks its neighbors. A neighbor already in seen is skipped. A new one goes into seen and onto todo. The loop is while todo:, which keeps going while the list is not empty (module 1: an empty list counts as false). When todo is empty, seen holds every reachable node.

    The trace builds the one-way lists for the pipeline, then spreads out from raw. todo is drawn standing up, with its top at the top. Before you step through, guess which table is popped right after clean.

    Step throughEvery table downstream of raw
    Step 1 of 55
    Line 1 is about to run.
    from collections import defaultdict
    def downstream(edges, start):
    graph = defaultdict(list)
    for a, b in edges:
    graph[a].append(b)
    seen = {start}
    todo = [start]
    while todo:
    node = todo.pop()
    for neighbor in graph[node]:
    if neighbor not in seen:
    seen.add(neighbor)
    todo.append(neighbor)
    return seen
    Names
    no names yet
    Output
    (nothing printed yet)

    Here is the spread in the four questions this course asks of every algorithm:

    Why seen is the whole answer when todo empties. A node enters seen only as a neighbor of a node already in seen, and the first node in seen is the start, so everything in seen is reachable. Every node in seen was pushed once. By the time todo is empty it has also been popped, and the round that popped it put all its neighbors in seen. So when todo is empty, no edge leads from a node in seen to a node outside it, and no path from the start can get out of seen: every reachable node is in it.

    seen also keeps the search from running forever. The pipeline does not show that: its edges are one-way and it has no cycle, so every route ends at a table nothing is built from. On a two-way edge, the search can step straight back to where it came from, and on a cycle it can come back the long way.

    Quick checkWithout seen

    Someone deletes the seen set and pushes every neighbor:

    todo = [start]
    while todo:
        node = todo.pop()
        for neighbor in graph[node]:
            todo.append(neighbor)

    What happens on the two-way graph {0: [1], 1: [0]} (one edge between 0 and 1) with start = 0?

    Choose one answer, then check.

    The cost line says each list entry is read at most once. Count the reads for yourself on a small two-way graph where every node is reachable.

    On paperCount the neighbor checks

    Run the spread by hand on this two-way graph, starting at 0. Count every neighbor check: each time the inner loop looks at one neighbor, whether it pushes it or skips it.

    graph = {0: [1, 2], 1: [0, 3], 2: [0], 3: [1]}

    Write seen and todo after each round (one pop and the checks of its neighbors), then reveal the steps one at a time.

    Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.

    neighbor checks

    Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.

    The problem below asks a yes-or-no version on a two-way graph: can you get from source to destination? You have every piece. Build the lists with an append in both directions, run the same spread from source, and return True the moment you pop the destination. Try it before you open the hints.

    easyDepth-first search target 15 min

    Is there a path

    A graph is a set of nodes joined by edges. This graph has n nodes, numbered 0 to n - 1. Each item [a, b] in the list edges is a two-way edge: you can step from a to b and from b to a.

    Return True if you can get from node source to node destination by stepping along edges, and False if you cannot. Every node can reach itself, so when source equals destination the answer is True.

    No edge is listed twice, and no edge joins a node to itself.

    Example 1
    Inputn = 6, edges = [[0, 1], [0, 2], [1, 3], [2, 3], [4, 5]], source = 0, destination = 3OutputTrue

    Step from 0 to 1, then from 1 to 3.

    Example 2
    Inputn = 6, edges = [[0, 1], [0, 2], [1, 3], [2, 3], [4, 5]], source = 1, destination = 5OutputFalse

    Nodes 4 and 5 are joined only to each other. No edge links them to nodes 0 to 3.

    Example 3
    Inputn = 1, edges = [], source = 0, destination = 0OutputTrue

    No step is needed to stay at node 0.

    Constraints
    • 1 ≤ n ≤ 2 × 105

    • 0 ≤ len(edges) ≤ 2 × 105

    • Each edge is [a, b] with 0 ≤ a, b ≤ n - 1 and a != b. No edge is listed twice.

    • 0 ≤ source, destination ≤ n - 1

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    The spread you wrote has a name. Taking the newest node next, as a stack does, makes it a depth-first search: it follows one route as far as it goes before it backs up. The next lesson studies that order. Swap the stack for a queue, which hands out the oldest item first, and the same code becomes breadth-first search, two lessons ahead. For reachability the order does not matter: either way, every reachable node ends up in seen.

    Last, say it the way you would in the room.

    Say itSay it like you would in the room

    An interviewer gives you a pipeline's lineage as an edge list, where [a, b] means table b is built from table a, and asks: if one table breaks, which tables are affected? Say your plan as you would before typing: the walk, the notebook, the promise and the cost.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: Depth-first search