Graph operations

Adding and removing vertices and edges · Part of Trees and graphs

Key idea

Practice

6 questions · about 3 min

Explained step by step

Adjacency matrix

With an adjacency matrix, adding or removing an edge is changing one cell: O(1). In an undirected graph you have to change both cells, M[i][j] and M[j][i], because the edge goes both ways. Building the matrix at the start costs O(n²), because all n × n cells have to be created, even if the graph has few edges.

With a matrix, adding a vertex is adding a row and a column full of 0s: O(n). Removing one is more expensive: its row and column have to go, and in the worst case, if it's the first, every other cell shifts up and to the left: (n − 1)² cells, O(n²). Matrices work well when the vertices hardly change.

Adjacency list

With adjacency lists, adding an edge is adding a neighbor to 2 lists: O(1). Removing an edge means finding it in the list: O(m) in the worst case. Adding a vertex is creating an empty list: O(1). Removing a vertex is the most expensive: its list goes, and the others' lists have to be walked removing the edges to it: O(n + m).

In practice, adjacency lists are usually kept in a hash table: the key is the vertex and the value is its list of neighbors. And vertices are represented as objects, not by their position number, because if position were used, removing vertex 3 would mean renumbering every later one in every list. With hash tables, the neighbor lists can also be swapped for hash sets, and removing an edge becomes about O(1).

The choice depends on the graph. If it's dense, with many edges, close to n², the matrix wastes no space and its edge operations are 1 step: it's the better fit. If it's sparse, with few edges, like almost every real network, lists take far less space. Hash-table lists seem to win everything in the theoretical table, but the matrix is faster in practice for edges, because it's 1 array access.

Graph

In summary, with n vertices and m edges: the matrix takes O(n²), handles edges in O(1), adds vertices in O(n) and removes them in O(n²). The list takes O(n + m), adds edges and vertices in O(1), removes edges in O(m) and vertices in O(n + m). With hash tables instead of lists, removing edges drops to O(1). Knowing this table lets you choose based on which operation happens most.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Adding and removing vertices and edges