Graph Basics

What a graph is, how to store one as an adjacency list or a grid, how directed and weighted graphs differ, and what interviewers ask about them.

15 minLesson 1 of 4
On this page
  1. Nodes, edges and the words used to describe them
  2. Storing a graph as an adjacency list
  3. Variants of the representation
  4. Pitfalls
  5. In the interview
  6. What to practise next

A graph is a set of items, called nodes, together with connections between pairs of them, called edges. It is the structure to use when the data is a network in which any item can connect to any other: roads between towns, friendships between people, "task A must run before task B", or the open cells of a maze. Almost every graph algorithm starts by turning the input into a form where you can ask "which nodes are next to this one?" quickly, and that is what this lesson covers.

An array only has a first and a last item, and a tree gives every node exactly one parent and allows no loops. Neither can represent two different routes between the same pair of towns, or a route that leads back to where it started, so a network stored in either one loses information.

Nodes, edges and the words used to describe them

The examples in this lesson use a small bus map with seven stops, A to G, and a bus line between some pairs of stops.

A B C D E F G degree 3 degree 1
The bus map as a graph with 7 nodes and 8 edges. C has degree 3, G has degree 1, and A, B, D and C form a cycle.
  • A neighbour of a node is a node joined to it by one edge. C's neighbours are A, D and E.
  • The degree of a node is the number of edges that touch it. C has degree 3 and G has degree 1.
  • A path is a sequence of nodes in which each consecutive pair is joined by an edge, such as A, C, E, F, G. Its length is the number of edges, which is 4 here.
  • A cycle is a path that returns to its starting node without reusing an edge. A, B, D, C, A is a cycle.
  • A graph is connected if every node can reach every other node. Otherwise it splits into separate pieces called components. If the road D–F closes, this map stays connected through E. If F–G closes, G becomes a component of its own.

A tree is a connected graph with no cycles, so what you learned in Tree Traversals carries over. The difference is the cycles: in a general graph you can walk back to a node you have already visited, so every walk through a graph has to remember which nodes it has seen.

Storing a graph as an adjacency list

Problems usually give the graph as an edge list, which is a list of pairs such as [["A","B"], ["A","C"], ...]. Finding the neighbours of C in that form means scanning every edge. An adjacency list avoids the scan: it is a map from each node to the list of its neighbours, so finding the neighbours of C is one lookup. In an undirected graph, each edge is added to the lists of both of its endpoints.

Build the adjacency list for the bus mapUse the arrows or ← → keys
for each stop: graph[stop] = []for each edge (u, v):  graph[u].append(v); graph[v].append(u)
  1. ABCDEFG
    A
    -
    B
    -
    C
    -
    D
    -
    E
    -
    F
    -
    G
    -

    1Start with an empty neighbour list for every stop, including any stop that might have no edges.

  2. ABCDEFG
    A
    B
    B
    A
    C
    -
    D
    -
    E
    -
    F
    -
    G
    -

    2Edge A–B is two-way, so B is added to A's list and A is added to B's list.

  3. ABCDEFG
    A
    B, C
    B
    A
    C
    A
    D
    -
    E
    -
    F
    -
    G
    -

    3Edge A–C adds C to A's list and A to C's list.

  4. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A
    D
    B
    E
    -
    F
    -
    G
    -

    4Edge B–D adds D to B's list and B to D's list.

  5. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A, D
    D
    B, C
    E
    -
    F
    -
    G
    -

    5Edge C–D closes the loop A, B, D, C, A, which a tree cannot contain.

  6. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A, D, E
    D
    B, C
    E
    C
    F
    -
    G
    -

    6Edge C–E gives C its third neighbour, so C's list is now longer than the others.

  7. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A, D, E
    D
    B, C, F
    E
    C
    F
    D
    G
    -

    7Edge D–F adds F to D's list and D to F's list.

  8. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A, D, E
    D
    B, C, F
    E
    C, F
    F
    D, E
    G
    -

    8Edge E–F adds F to E's list and E to F's list.

  9. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A, D, E
    D
    B, C, F
    E
    C, F
    F
    D, E, G
    G
    F

    9Edge F–G is the last edge, and G ends up with a single neighbour.

  10. ABCDEFG
    A
    B, C
    B
    A, D
    C
    A, D, E
    D
    B, C, F
    E
    C, F
    F
    D, E, G
    G
    F
    list entries
    16

    10All 8 edges are stored as 16 list entries, and C's neighbours can now be read from one short list.

1 / 10
// nodes: list of names. edges: list of [u, v] pairs, two-way.
function buildGraph(nodes, edges) {
  const graph = {};
  for (const node of nodes) graph[node] = [];
  for (const [u, v] of edges) {
    graph[u].push(v);
    graph[v].push(u); // leave this line out for a directed graph
  }
  return graph;
}
 
const graph = buildGraph(
  ["A", "B", "C", "D", "E", "F", "G"],
  [["A", "B"], ["A", "C"], ["B", "D"], ["C", "D"],
   ["C", "E"], ["D", "F"], ["E", "F"], ["F", "G"]]
);
graph["C"]; // ["A", "D", "E"]
# nodes: list of names. edges: list of (u, v) pairs, two-way.
def build_graph(nodes, edges):
    graph = {node: [] for node in nodes}
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u)  # leave this line out for a directed graph
    return graph
 
graph = build_graph(
    ["A", "B", "C", "D", "E", "F", "G"],
    [("A", "B"), ("A", "C"), ("B", "D"), ("C", "D"),
     ("C", "E"), ("D", "F"), ("E", "F"), ("F", "G")],
)
graph["C"]  # ['A', 'D', 'E']
TimeO(V + E) to build
SpaceO(V + E)

V is the number of nodes and E the number of edges. There is one empty list per node and two entries per edge. Reading one node's neighbours costs the size of its list.

Variants of the representation

Directed graphs

In a directed graph each edge has a direction, like a one-way street, a "follows" relationship, or a requirement that task X is finished before task Y. The edge [u, v] is stored only in graph[u], which is why the second push in the code above is marked as the line to remove. Many problems that look undirected are directed, and the usual sign is a word like "depends on", "follows" or "must come before". Directed graphs are the setting for Topological Sort.

In a directed graph the degree splits in two. The out-degree of a node is the number of edges that leave it, and the in-degree is the number of edges that arrive at it. The adjacency list above gives out-degrees directly, and in-degrees have to be counted by reading every list once. A graph can also contain a self-loop, an edge from a node to itself, and parallel edges, two edges between the same pair of nodes. Check whether the problem allows them, because a self-loop counts as a cycle and parallel edges put the same neighbour into a list twice.

Weighted graphs

In a weighted graph each edge carries a number, such as travel time or price. The adjacency list then stores a pair for each neighbour, the neighbour and the weight of the edge to it, for example graph["A"] = [["B", 4], ["C", 2]]. Structure and weights are otherwise handled the same way. Shortest routes in weighted graphs are the subject of Dijkstra's algorithm. If every edge counts as one step, as in a maze, you do not need weights at all.

Adjacency matrix

An adjacency matrix is a V × V table in which the entry at row u and column v is true (or holds the weight) when there is an edge from u to v. It answers "is there an edge between u and v?" in one step, but it always uses V² cells, and listing the neighbours of one node means reading a whole row of V cells. Most graphs in problems are sparse, which means each node has only a few neighbours, so a matrix wastes almost all of its space. Use a matrix only when the graph is dense, meaning E is close to V², or when V is small and the algorithm asks about arbitrary pairs of nodes, as Floyd-Warshall does.

Edge list

Keeping the graph as a plain list of edges takes O(E) space and is the input format of most problems. It is also the form that some algorithms want directly, such as Kruskal's algorithm in Minimum Spanning Trees, which sorts the edges by weight. For anything that repeatedly asks for the neighbours of a node, convert it to an adjacency list first.

Grids

A maze, a game board, a map of land and water and an image all arrive as a 2D grid. You can treat each cell as a node whose neighbours are the cells above, below, left and right of it, as long as they are inside the grid and not a wall. A grid with R rows and C columns has R × C nodes and at most four edges per node, so it is sparse.

(0, 0) (0, 1) # (0, 3) (1, 0) (1, 1) (1, 2) (1, 3) (2, 0) (2, 1) (2, 2) # row 0 row 1 row 2 col 0 col 1 col 2 col 3
Cell (1, 1) in a 3 × 4 grid has four neighbours. A cell on the border has fewer, and a wall (#) is never a neighbour.

You do not build an adjacency list for a grid, because the neighbours follow from the position. For each of the four direction offsets, add it to the row and column and keep the result if it is inside the grid and not a wall. Every graph algorithm in this module then works on the grid by calling this function wherever the algorithm says "for each neighbour".

const DIRS = [[-1, 0], [1, 0], [0, -1], [0, 1]]; // up, down, left, right
 
function gridNeighbours(grid, r, c) {
  const result = [];
  for (const [dr, dc] of DIRS) {
    const nr = r + dr;
    const nc = c + dc;
    const inside = nr >= 0 && nr < grid.length && nc >= 0 && nc < grid[0].length;
    if (inside && grid[nr][nc] !== "#") result.push([nr, nc]);
  }
  return result;
}
 
const grid = ["..#.", "....", "...#"];
gridNeighbours(grid, 1, 1); // [[0, 1], [2, 1], [1, 0], [1, 2]]
gridNeighbours(grid, 0, 3); // [[1, 3]]
DIRS = [(-1, 0), (1, 0), (0, -1), (0, 1)]  # up, down, left, right
 
def grid_neighbours(grid, r, c):
    result = []
    for dr, dc in DIRS:
        nr, nc = r + dr, c + dc
        inside = 0 <= nr < len(grid) and 0 <= nc < len(grid[0])
        if inside and grid[nr][nc] != "#":
            result.append((nr, nc))
    return result
 
grid = ["..#.", "....", "...#"]
grid_neighbours(grid, 1, 1)  # [(0, 1), (2, 1), (1, 0), (1, 2)]
grid_neighbours(grid, 0, 3)  # [(1, 3)]

When a graph is not the right model

If the data is a hierarchy in which every item has one parent, such as a file system or an org chart, a tree is enough and the tree algorithms are simpler. If the items are only compared by size or arrive in sequence, an array or a heap fits better. A graph is worth building when the connections themselves decide the answer, for example whether two nodes are connected or how many steps lie between them.

Pitfalls

In the interview

A graph problem rarely uses the word "graph". Look for items with connections between pairs of them: cities and roads, people and friendships, courses and prerequisites, words that differ by one letter, or cells of a grid that you can move between. Phrases such as "is there a way to get from", "fewest steps", "number of groups" or "can all tasks be finished" point to a graph, and the next step is to say what the nodes and edges are. Once you have said that, pick the algorithm: breadth-first search for the fewest steps and depth-first search for reachability or counting groups.

Questions to expect:

  • "How would you store this graph?" An adjacency list, because it uses O(V + E) space and gives the neighbours of a node directly. Mention that a matrix would take V² space, which is wasteful when each node has few neighbours.
  • "When would you use an adjacency matrix instead?" When the graph is dense or small and the algorithm often asks whether a particular edge exists, since the matrix answers that in O(1). A list needs a scan of the node's neighbours, or a set per node if you need the same speed.
  • "Is the graph directed? Can it have cycles or disconnected parts?" You are expected to ask this before coding. It decides whether an edge is stored once or twice, whether a search needs a visited set, and whether you must start the search from every node to cover all components.
  • "Given n nodes and a list of edges, how do you check that the graph is a tree?" A tree has exactly n - 1 edges and is connected. If the edge count is n - 1, it is enough to check either that the graph is connected or that it has no cycle, because one of those facts implies the other.
  • "What are the nodes and edges in a grid problem?" Each cell is a node, and each in-bounds, non-wall neighbour in the four directions is an edge. Say that you will compute neighbours with direction offsets instead of building a list, and mention the diagonal moves if the problem allows them.
  • "What is the cost of building the graph?" O(V + E) time and space, because it creates one list per node and adds one or two entries per edge. This cost is paid before any search, and the search itself is usually O(V + E) as well.
  • "The nodes are strings or arbitrary ids. How do you handle that?" Use a hash map from the id to its neighbour list, as in the code above. If the ids are the integers 0 to n - 1, an array of lists is simpler and faster.
Quick check

An undirected graph has 5 nodes and 6 edges, stored as an adjacency list. How many entries are there across all the neighbour lists?

In a grid with 3 rows and 4 columns and no walls, how many neighbours does the corner cell (0, 0) have?

A social app has 10 million users, and each follows about 200 others. Which storage fits?

What to practise next

Next, learn to walk a graph with Breadth-First Search, which finds the fewest-stops trip from A to G on this bus map and works on grids as well, and then Depth-First Search.